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

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

结果是

http://img1.mukewang.com/63832cd90001807e06460158.jpg

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


fetch("https://google.com", { mode: "no-cors" })

  .then(response => response.text())

  .then(data => console.log(data));

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


青春有我
浏览 116回答 3
3回答

炎炎设计

像这样尝试: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();您需要等待承诺,这意味着您需要一个异步函数。

哔哔one

fetch 将返回一个承诺,而不是一个字符串。在你的第二个例子中,你调用.text()它。你将不得不在 asyc/await 中做类似的事情

ITMISS

使用t.then(res => console.log(res));它将返回response对象。因为你有async功能test而且你没有await像await test()这样它会返回promise。根据您的评论,您应该使用await test(). 但是你只能await在内部使用,async所以我建议使用如下的包装函数。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();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript