为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

青春有我 2022-11-27 17:24:18
首先,我确保为我在这里谈论的问题编写一个快速演示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。
查看完整描述

3 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

像这样尝试:


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

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


查看完整回答
反对 回复 2022-11-27
?
哔哔one

TA贡献1854条经验 获得超8个赞

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



查看完整回答
反对 回复 2022-11-27
?
ITMISS

TA贡献1871条经验 获得超8个赞

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


查看完整回答
反对 回复 2022-11-27
  • 3 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信