如何在不使用 .then 语法的情况下使 fetch Promise 解析?

ark*_*k0n 3 javascript promise es6-promise fetch-api isomorphic-fetch-api

首先,我确保为我在这里讨论的问题编写一个快速演示https://codesandbox.io/s/exciting-swirles-7cs3s

但本质上,使用该isomorphic-fetch库,我遇到了一个问题,我无法真正获得该函数的值,或者你可能会说,分辨率fetch()

import fetch from "isomorphic-fetch";

async function test() {
  return await fetch("https://google.com", { mode: "no-cors" });
}

let t = test();
console.log(t);
Run Code Online (Sandbox Code Playgroud)

其结果是

在此输入图像描述

fetch()现在我也考虑了像这样的其他使用方式

fetch("https://google.com", { mode: "no-cors" })
  .then(response => response.text())
  .then(data => console.log(data));
Run Code Online (Sandbox Code Playgroud)

它实际上传递了一个字符串,但如果可能的话,我更喜欢用第一种方法?我也很可能没有正确使用 fetch。

see*_*per 5

试试这样:

import fetch from "isomorphic-fetch";

async function test() {
  const response = await fetch("https://google.com", { mode: "no-cors" });
  return response.text();
}
async function main() {
  let t = await test();
  console.log(t);
}
main();
Run Code Online (Sandbox Code Playgroud)

您需要等待承诺,这意味着您需要一个异步函数。

  • 选择你的毒药@notacorn。.thens 很尴尬,但唯一的选择是 async-await,它需要包装函数。在这种情况下,您当然可以将这两个函数合二为一。 (2认同)