I’m having a hard time understanding the execution order of the code that has asynchronous elements in it. Here’s the problematic code:
const promise = new Promise(function(resolve, _){
resolve('microtask2');
}).then((res)=> {
console.log(res);
}).catch((err)=> console.error(`caught an ${err}`));
const timer = setTimeout(function(){
console.log('set timeout');
}, 0);
for(let i = 0; i < 1000; i++){
console.log(`cicle 1: ${i}`);
}
const result = await new Promise(function(resolve, _){
try{
resolve('microtask1');
}
catch(err){
console.error(`caught an ${err}`);
}
});
for(let i = 0; i < 1000; i++){
console.log(`cicle 2: ${i}`);
}
At the beginning I thought that event loop executes code in the following order:
- all synchronous code
- microtask queue
- macrotask queue
And it appears to work exactly so if I comment out result
promise:
output: loop1 --> loop2 --> microtask2 --> set timeout
But if I keep the result
the callback from multitask is printed out in between the loops (where it is defined) without waiting for all the synchronous code to finish:
output: loop1 --> microtask2 --> loop2 --> set timeout
What am I missing here? Is this behaviour somehow related to the blocking nature of await
?