I am new to JS and am trying to figure out the execution order when the code has microtasks. I know the theroy that the microtasks are pushed to the queue when the stack is “empty” (i.e. when there is only global context on it).
For example, in the global context we have two consecutive loops:
for(let i = 0; i<1000; i++){
console.log(i);
};
for(let i = 0; i<1000; i++){
console.log(i);
};
Is it true that before, after and during the execution of the for-loops the condition of the stack being empty is fulfilled? If yes, why is the microtask (res)=> { console.log(res)}
in the following code not executed between the last two loops if by that time it is in the queue and the call stack is empty?
const promise = new Promise(function(resolve, _){
resolve('microtask2');
});
for(let i = 0; i<1000; i++){
console.log(i);
};
promise.then((res)=> {
console.log(res);
)};
for(let i = 0; i<1000; i++){
console.log(i);
};
for(let i = 0; i<1000; i++){
console.log(i);
};
Here’s how I see the execution order:
- The executor function inside the promise’s constructor calls
resolve()
and settles the promise immediately. - A loop is executed.
then()
is evoked, it’s context put on the call stack (on top of the global context)- The callback inside
then()
is registered somewhere in the browser’s environment. then
context pops off the stack.- Another loop is executed, as the callback from
then()
was only registered and is not yet in the queue (or does it go to the queue immediately?) - Now that the loop is finished and the call stack is empty, event loop picks up the callback from the queue tosses it to the call stack and executes (I know it is not the case and the callback is going to be printed last, but I don’t know why)
- The last loop is executed
By the step 7 all the condition for the callback to be executed are fulfilled:
a) there is nothing on the stack
b) no synchronous code is running
c) the callback is waiting in the queue
Why is the callback sitting in the queue until the final loop is executed if there are plenty of oportunities to be executed between the loops?