The blog is very helpful but the outputs of 2 small code snippets in your blog is where i am getting confused. Could you please tell me where I am going wrong ? Your help will be REALLY valuable. Im getting confused in process.nextTick() .
I think because process.nextTick is in fs.readFile block, so when event loop comes to poll phase, it has to wait for i/o task is completed before executing anything else so every callbacks in this block are put to corresponding phase queue, now, there is nothing to do more in this phase, the event loop will move to check phase and print 5 to console, next iteration when event loop comes to i/o phase, it check that i/o task is done so it prints 'process.nextTick' -> check phase( print '4') -> closing phase -> timer phase (print '3')
Hey! Pardon for the late reply. As trunghahaha said, process.nextTick is wrapped inside the fs.readFile, hence, the event loop gets to know about it only when the callback of fs.readFile is executed, right? Hence, such behaviour.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hi,
The blog is very helpful but the outputs of 2 small code snippets in your blog is where i am getting confused. Could you please tell me where I am going wrong ? Your help will be REALLY valuable. Im getting confused in process.nextTick() .
In the above code all the callbacks from microtasks queue are executed first so the below output :
2
4
3
1
But in the the last code snippet you mentioned as example :
}
main();
In the above code process.nextTick does not seem to be executed first as seen in the below output :
1
2
5
process.nextTick
4
3
close callback
Could you please explain why process.nextTick is not being executed first ??
I think because process.nextTick is in fs.readFile block, so when event loop comes to poll phase, it has to wait for i/o task is completed before executing anything else so every callbacks in this block are put to corresponding phase queue, now, there is nothing to do more in this phase, the event loop will move to check phase and print 5 to console, next iteration when event loop comes to i/o phase, it check that i/o task is done so it prints 'process.nextTick' -> check phase( print '4') -> closing phase -> timer phase (print '3')
Okay ! Did not read the code carefully that's y d confusion . Thanks a lot :)
Hey! Pardon for the late reply. As trunghahaha said, process.nextTick is wrapped inside the fs.readFile, hence, the event loop gets to know about it only when the callback of fs.readFile is executed, right? Hence, such behaviour.