javascript - JS - then 与 async / await 返回值
问题描述
我试图将我的“问题”简化为更简洁。我正在尝试从异步函数中返回(获取必须在特定函数中,因为我正在那里进行其他调用)。
单击按钮时会触发 testAsync :
async function testAsync(){
console.log("start async");
let result = await go(); // Waiting promise
console.log("result "+result);
alert(result);
}
然后我想做“去”的事情
async function go(){
fetch('https://apiurl.com', {
method: 'POST',
body: '{"URL":"anotherurltotest.com"}'
})
.then(response => response.json())
.then(json => {return json;})
.catch(err => {
console.log(err)
})
}
使用此方法:结果未定义并立即触发,而不是等待 then/fetch 的返回 json。
但我试过这个:
async function go(){
return await fetch('https://apiurl.com', {
method: 'POST',
body: '{"URL":"anotherurltotest.com"}'
})
.then(response => response.json())
.catch(err => {
console.log(err)
})
}
这样,结果仅在短时间内被触发并被填充。
为什么当时的回报不起作用?但回来等待所有的取货,是吗?
谢谢 :)
解决方案
推荐阅读
- excel - 在excel中合并两行,并在最后一列旁边移动一列
- php - 在 Laravel 中将多个数据一次保存到数据库中
- rust - 将 Unix 套接字与 socket2 一起使用
- java - 如何仅将对象的几个字段用于 REST 服务
- selenium - 使用 Selenium、IEDriverServer 通过 Java 执行测试时出现“IE 驱动程序的命令行服务器已停止工作”错误
- python-3.x - Tkinter 网格传播和滚动条
- hyperledger-fabric - Hyperledger Fabric 1.2 服务发现无法在启用 TLS 的情况下工作
- wordpress - Avada 自定义 CSS 设置未生效
- unity3d - ARCore如何在Unity中设置点云
- php - 分解为数组并将每个元素打印为列表项?