gpt4 book ai didi

javascript - 使用 setTimeout 连续异步/等待

转载 作者:行者123 更新时间:2023-11-28 17:27:14 25 4
gpt4 key购买 nike

我是 ES6 的新手,所以我研究了 Javascript 的语句。

在测试 async/await 时,我发现了一些奇怪的行为。

我写的代码是这样的,

const test = async () => {
await setTimeout(() => {
console.log("timeout");
}, 2000);
await console.log(1);
await console.log(2);
}

test();

输出在这里,

1
2
timeout
[Finished in 2.1s]

我定义 async 来运行,并等待每一行进行同步工作。

预期输出在这里,

timeout
1
2
[Finished in 2.1s]

为什么这段代码不能同步工作?

谢谢。

最佳答案

这就是您获得所需输出的方法。您可以将 setTimeout 包装在 Promise 中并await 它。

const test = async () => {
await new Promise((resolve)=>setTimeout(() => {
console.log("timeout");
resolve();
}, 2000));
console.log(1);
console.log(2);
}

test();

关于javascript - 使用 setTimeout 连续异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51275801/

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