I have read the official documentation and the many other blogs on process.nextTick() but I am a little confused on certain topics.
Firstly, it is written that the callbacks in process.nextTick() are executed before the start of next iteration.
Secondly, when inside an I/O cycle, the event loop is currently in the poll phase. And after the poll phase the event-loop moves to the check phase where any callbacks called in setImmediate method are executed.
Now in the following code
const fs = require('fs');
function main() {
fs.readFile('./xy.txt', function(err, buff){
setTimeout(()=> console.log("timeout inside fs"),0);
setImmediate(()=> console.log("immediate inside fs"));
process.nextTick(()=>{console.log("process.nextTick")});
console.log("inside fs");
})
console.log("called inside main fn in first-iteration");
}
main();
console.log("called in first-iteration);
The output would be:
called inside main fn in first-iteration
called in first iteration
During this the callback of the fs fn would be registered and the above two lines would be consoled as the entry script would be run without event-loop. And now the first-iteration of event loop will start, starting from the timer phase, as no timers are present it will move to the pending phase and then to the poll phase, where-in there is a callback (fs fn callback), the event-loop starting executing the fs callback and now the setTimeout callback and setImmediate callback would be registered. After that, the process.nextTick callback will be registered in the nextTickQueue which will be executed in the next iteration or tick (second iteration). Now after the poll phase ends, we have inside fs logged on the third line.
Next the event loop should move to check phase, where the setImmediate callback is present and should log immediate inside fs following that the event-loop should move on to the next-phases and the first iteration should end. Before starting the second iteration, process.nextTick should be logged and then timeout inside fs should be logged at last.
Thus making the final output to be:
called inside main fn in first-iteration
called in first iteration
inside fs
immediate inside fs
process.nextTick
timeout inside fs
But instead the output is coming out to be:
called inside main fn in first-iteration
called in first iteration
inside fs
process.nextTick
immediate inside fs
timeout inside fs
somewhere it was written that the microtasks (process.nextTick) are executed on top priorty and so the event loop will leave all its execution and execute the microtask at first glance. But if that too is the case, why is inside fs consoled before process.nextTick?
Basically, I am confused, how does process.nextTick() and the event-loop flow through phases go on?
