首页 > 解决方案 > 等待 fetch 在 Javascript 中无法按预期工作

问题描述

为什么下面代码的输出 Promise {<pending>}不是Response. 我做错了什么?await fetch("https://...")也不工作。

function asynchronousFunction() {
  return fetch("https://thatcopy.pw/catapi/rest/")
}

const mainFunction = async () => {
  const result = await asynchronousFunction()
  return result;
}
console.log(mainFunction())

标签: javascriptasynchronousasync-await

解决方案


您不应该将 Promises 和异步函数(返回 Promises)视为可用于在顶层返回值的东西。来自命令式和同步编程的思维方式通常是一个坏主意。

改用链接,或者移动console.loginside mainFunction,或者这样写:

asynchronousFunction()
  .then(console.log)

推荐阅读