我怎么能让这段代码等待第一个函数执行之前完成第二个或函数以更少的秒?


setTimeout(() => {console.log("this is the first message")}, 5000);
setTimeout(() => {console.log("this is the second message")}, 3000);
setTimeout(() => {console.log("this is the third message")}, 1000);

我怎样才能使这段代码等待第一个函数完成,然后再执行第二个函数或用更少的时间执行函数?

function delay(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
}
delay(1000)
.then(() => alert("Hello!"))

也可以设置为async/await

有人说…async await?

const wait = ms => new Promise(r => setTimeout(r, ms));
(async () => {
console.log("this is the first message");
await wait(5000);
console.log("this is the second message");
await wait(3000);
console.log("this is the third message");
await wait(1000);
})();

最新更新