What's the difference between process.nextTick() and setImmediate()?

I found this question mentioned above on this wbesite and in many different websites, and as an answer there is mentioned:

The difference between process.nextTick() and setImmediate() is that process.nextTick() defers the execution of an action till the next pass around the event loop or it simply calls the callback function once the ongoing execution of the event loop is finished whereas setImmediate() executes a callback on the next cycle of the event loop and it gives back to the event loop for executing any I/O operations.

I found the answer is a little bit sophisticated and is not clear, what I understand is the process.nextTick() has the highest priority to execute the code when it setImmediate() exists.

function nextTickCb() {
    console.log('Processed nextTickCb');
}

function immediateCb() {
    console.log('Processed immediateCb');
} 

setImmediate(immediateCb)
process.nextTick(nextTickCb);
console.log('Process in the first Iteration')

The code returns:

Process in the first Iteration
Processed nextTickCb
Processed immediateCb

According to Node.js official documentation, process.nextTick() will be executed after the current operation is completed, regardless of the current phase of the event loop.

No Comments Yet