gpt4 book ai didi

javascript - 在多个 settimeout 上使用 Async/Await

转载 作者:行者123 更新时间:2023-12-03 23:58:17 25 4
gpt4 key购买 nike

为了理解 async/await,我试图在 settimeout 运行并到期后显示控制台消息。如何在下面修复我的代码?我有 5 个 settimeout 函数,每个函数都应该在完成后显示各自的消息。

function t1(){
setTimeout(() => {
console.log("1")
}, 1000);
}

function t2(){
setTimeout(() => {
console.log("2")
}, 2000);
}

function t3(){
setTimeout(() => {
console.log("3")
}, 3000);
}

function t4(){
setTimeout(() => {
console.log("4")
}, 4000);
}

function t5(){
setTimeout(() => {
console.log("5")
}, 5000);
}

async function main(){
await t1();
console.log("1sec done");
await t2();
console.log("2sec done");
await t3();
console.log("3sec done");
await t4();
console.log("4sec done");
await t5();
console.log("Yay! I am all done");
}
main();

最佳答案

您应该使用 Promises

function t1(){
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log("1");
resolve();
}, 1000);
});
}

function t2(){
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log("2");
resolve();
}, 1000);
});
}

function t3(){
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log("3");
resolve();
}, 1000);
});
}

function t4(){
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log("4");
resolve();
}, 1000);
});
}

function t5(){
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log("5");
resolve();
}, 1000);
});
}

async function main(){
await t1();
console.log("1sec done");
await t2();
console.log("2sec done");
await t3();
console.log("3sec done");
await t4();
console.log("4sec done");
await t5();
console.log("Yay! I am all done");
}
main();

关于javascript - 在多个 settimeout 上使用 Async/Await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55256133/

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