gpt4 book ai didi

node.js - Node 中的 async/await 实现

转载 作者:太空宇宙 更新时间:2023-11-03 22:50:27 24 4
gpt4 key购买 nike

我正在尝试在我的代码中实现异步/等待。但我对此有疑问。

代码:

const a = async() => {
var Param = { key: 'xxx' };
const authusers = await func1(Param);
await console.log("hello world");
}

func1() {
dbquery {
console.log(results);
return results;
}
}

根据我对async/await的理解,即只有在第一个await函数之后才会执行第二个await函数,那么结果将是这样的:

结果

Hello World

但结果显示为:

Hello World 结果

最佳答案

async/await 与 Promise 配合使用,因此您不能只返回结果,您需要返回 Promise。

您不需要“像控制台日志一样”等待同步代码,只需等待您的 promise 函数即可。

const a = async() => {
var Param = { key: 'xxx' };
const authusers = await func1(Param);
console.log(authusers)
console.log("hello world");
}

const func1 = (param) =>{
return new Promise(resolve =>{
setTimeout(() =>{
return resolve('waited')
},1000)
})


}
a()

关于node.js - Node 中的 async/await 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48182055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com