Sye*_*b M 1 node.js async-await
我有以下代码片段async/await.
async function test1 () {
setTimeout(() => {
console.log("1")
}, 2000);
}
async function test2 () {
setTimeout(() => {
console.log("2")
}, 1000);
}
async function test3 () {
setTimeout(() => {
console.log("3")
}, 1500);
}
async function test4 () {console.log("4")}
async function run () {
await test1()
await test2()
await test3()
await test4()
}
run()
Run Code Online (Sandbox Code Playgroud)
当我探索上面的代码片段时,我期待输出为1,2,3,4.但我得到了4,2,3,1.我错过了什么吗?
节点版本 v10.13.0
await荷兰国际集团test1等是相同的await荷兰国际集团setTimeout(...)直接.setTimeout不是以承诺为基础,在承诺链中不予考虑.
await test1()等等导致一次延迟,run()承诺立即解决.
为了使代码按预期工作,它应该是:
function test1 () {
return new Promise(resolve => setTimeout(() => {
console.log("1");
resolve();
}, 2000));
}
Run Code Online (Sandbox Code Playgroud)
test1等等,不需要async因为他们无法从async功能创造的承诺中受益.
| 归档时间: |
|
| 查看次数: |
23 次 |
| 最近记录: |