Hid*_*ide 1 javascript async-await ecmascript-6
我是 ES6 的新手,所以我研究了 Javascript 的声明。
在测试 async/await 时,我发现了一些奇怪的行为。
我写了这样的代码,
const test = async () => {
await setTimeout(() => {
console.log("timeout");
}, 2000);
await console.log(1);
await console.log(2);
}
test();
Run Code Online (Sandbox Code Playgroud)
输出在这里,
1
2
timeout
[Finished in 2.1s]
Run Code Online (Sandbox Code Playgroud)
我将 async 定义为功能并等待每一行同步工作。
预期输出在这里,
timeout
1
2
[Finished in 2.1s]
Run Code Online (Sandbox Code Playgroud)
为什么这段代码不能同步?
谢谢。
这就是您如何获得所需的输出。您可以将您的包裹setTimeout
在 aPromise
和await
it 中。
const test = async () => {
await new Promise((resolve)=>setTimeout(() => {
console.log("timeout");
resolve();
}, 2000));
console.log(1);
console.log(2);
}
test();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8837 次 |
最近记录: |