I am seeing an unexpected output when running some functions using async/await which I can’t work out.
The code looks like:
const delayToRun = async() => {
console.log('first delay');
let p = await new Promise((resolve, reject) => {
setTimeout(() => resolve('Done'), 2000);
});
console.log('second delay');
return p;
};
const start = async() => {
for (let i = 0; i < 2; i++) {
const res = await delayToRun();
console.log(res);
console.log('--------------------------------');
}
};
start();
start();
Output:
first delay
first delay
second delay
Done
--------------------------------
first delay
second delay
Done
--------------------------------
first delay
second delay
Done
--------------------------------
second delay
Done
--------------------------------
For me it would make sense that all blocks display: first, second, Done.
But the first one seems to start at the beginning then complete at the end.
Can someone shed some light on this please?
Thanks
2
Answers
You’re not
await
-ing yourstart()
function, so the second instance ofstart()
is triggered immediately after the first one.For comparison:
You’re running
start()
twice, independently, concurrently, since they don’t wait for each other. It might help to understand the behaviour by printing the source of each log line to better distinguish them:From the output, you can see that actually they execute in lockstep.