Reputation: 1817
I have following code snippet with 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()
When I explore above code snippet, I am expecting output as 1, 2, 3, 4. But I got 4, 2, 3, 1. Am I missed anything here?
Node Version v10.13.0
Upvotes: 1
Views: 36
Reputation: 223064
await
ing test1
, etc. is the same as await
ing setTimeout(...)
directly. setTimeout
is not promise-based and isn't taken into account in promise chain.
await test1()
, etc. result in one-tick delays, run()
promise resolves instantly.
In order for the code to work as intended, it should be:
function test1 () {
return new Promise(resolve => setTimeout(() => {
console.log("1");
resolve();
}, 2000));
}
test1
, etc. don't need to be async
because they cannot benefit from a promise created by async
function.
Upvotes: 5