javascript - 等待 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())
解决方案
您不应该将 Promises 和异步函数(返回 Promises)视为可用于在顶层返回值的东西。来自命令式和同步编程的思维方式通常是一个坏主意。
改用链接,或者移动console.log
inside mainFunction
,或者这样写:
asynchronousFunction()
.then(console.log)
推荐阅读
- javascript - 基于js中的点击将php值传递给其他php文件
- powershell - 使用 Chocolatey 安装软件的 PowerShell 脚本
- android - 在 Android 10 及更低版本上仅使用设备凭据选项显示身份验证提示
- javascript - 在日历JS中搜索日期
- angular - 打字稿:输入显示两个值(一个不会考虑)
- c++ - 为什么删除重载时需要使用声明
- azure-devops - Azure DevOps 审核日志 Group.CreateGroups 为未经许可的用户以 [TEAM FOUNDATION] 为前缀的组
- javascript - 即使单击提交按钮后也不会调用 onSubmit 函数
- python-3.x - 使用 python 的 jira 服务台 api 上的 401 错误
- javascript - 功能组件反应中文档上的 removeEventListener 不起作用