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

How to make fetch promise resolve without using .then syntax?

首先,我确保为我在这里讨论的问题写了一个快速演示 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);

结果是

现在我也考虑过像这样使用fetch()的另一种方式

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

这实际上提供了一个字符串,但如果可能的话,我更喜欢第一种方式?也很有可能是我没有正确使用fetch。

fetch 将 return 一个承诺,而不是一个字符串。在您的第二个示例中,您对其调用 .text() 。你将不得不在 asyc/await

中做类似的事情

这样试试:

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();

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

使用t.then(res => console.log(res));它将return response对象。

因为你有 async 功能 test 而你没有 awaitawait test() 那样使用它,所以它会 return promise

根据您的评论,您应该使用 await test()。但是你只能在 async 中使用 await 所以我建议使用如下的包装函数。

import fetch from "isomorphic-fetch";

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

async function wrapper() {  
  let t = await test();
  console.log(t.text());
}

wrapper();