These are quote from Nodejs documentation and blogs.
If an immediate timer is queued from inside an executing callback, that timer will not be triggered until the next event loop iteration.
setImmediate() will always be executed before any timers if scheduled within an I/O cycle, independently of how many timers are present.
According to Node docs, setImmediate()'s callback should be executed in next tick. However, when it's scheduled in the I/O(aka poll phase), setImmediate's callback is always triggered before timer.
fs.readFile('xx', () => {
setTimeout(() => { console.log('2 timeout'); }, 0);
setImmediate(() => { console.log('1 Immediate'); });
});
> 1 Immediate
> 2 timeout
My question is how does it work exactly? Does setImmediate()'s callback executed in current tick instead of next tick thus it logs before timer?
Note: I have read all the suggested existing posts but I don't see any post talking about this particular use case where setImmediate is scheduled under I/O phase.