gpt4 book ai didi

Javascript 异步/等待程序顺序

转载 作者:行者123 更新时间:2023-12-03 01:00:48 26 4
gpt4 key购买 nike

const function1 = () => 
new Promise(function(resolve,reject) {
setTimeout(() => {
resolve(10)
},6000)
});

const function2 = async () => {
console.log("first");

const val = await function1()
console.log("second");
return val
}

console.log("third -- " ,function2())

我期望消息的顺序如下:

first
second
third -- Promise { <pending> }>

但结果给出了以下输出:

first 
third -- Promise { <pending> }
second

谁能帮我理解这一点吗?

最佳答案

您需要await,而不是调用function2()

    await function2(); // logs first (6 seconds expire) second, 10

这是因为你需要等待函数 2 解析 Promise 才能继续

您可以执行以下操作以获得所需的结果

    const function3 = async () => {
const third = await function2();
console.log( "third --", third )
}
function3();

关于Javascript 异步/等待程序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52630823/

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