gpt4 book ai didi

javascript - 异步/等待不工作

转载 作者:行者123 更新时间:2023-11-30 08:26:11 25 4
gpt4 key购买 nike

我试图先让 Number 1 进入 console.log,但事实并非如此。我做错了什么?

谢谢。

let timer = function(time, message) {
setTimeout((time) => {
console.log(`ALERT: ${message}`);
}, time);
//return time;
}

const asyncDemo = async function asyncDemo(time, message) {
try {
var time1 = await timer(3000, "Number 1");
} catch (e) {
console.log("Critical error!");
}
try {
var time2 = await timer(1000, "Number 2");
} catch (e) {
console.log("Critical error!");
}
}

asyncDemo();

最佳答案

Ansync/Await 依赖于 promise 来工作。所以你的函数需要返回一个 promise 。例如:

let timer = function(time, message) {
return new Promise((resolve, reject) =>{
setTimeout((time) => {
console.log(`ALERT: ${message}`);
resolve()
}, time);

})
}

关于javascript - 异步/等待不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45316695/

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