I was going through the event loop in JavaScript and how it makes the JS to perform asynchronous operations even though it is a single threaded language. In that I learnt that the microtasks or process.nextTick run whenever the call stack is empty and between every phase.
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('first timeout');
resolve('1');
},1000);
console.log('2');
setTimeout(() => {
console.log('3');
},1000);
});
myPromise.then((value) => {
console.log("First then received:", value);
setTimeout(() => {
console.log('5');
},0);
}).catch((error) => {
console.log("Caught in catch:", error);
});
In the above code I was expecting the output to be
2
first timeout
First then received: 1
3
5
because the setTimeout-5 function will be pushed to the macroTask queue after the setTimeout-3 because “only resolving object will be mictoTask” and microTasks will execute after the synchronous code executes.
but the output when I try to run in node version 23 is
2
first timeout
First then received: 1
5
3
Is there a fault in my understanding? where am I missing?