This article is a short follow up to my original article series about Node.js Event Loop. In the original article series, I discussed in detail about Timers,
process.nextTick, Promises and many more.
However, since Node.js v11.0.0, there are some significant changes to the behavior of
process.nextTick and Promises. In this article, I’m going to discuss these new changes along with some comparisons of the functionality between Node < v11.0.0 and Node ≥ v11.0.0. If you miss any of my previous articles about Node.js Event loop, I recommend you read them from the following links and return here to see the new changes introduced in Node v11.0.0.
- Reactor Pattern and the Big Picture
- Timers and Immediates
- Promises, Next-Ticks and Immediates
- Handling I/O
- Event Loop Best Practices
If you run the following piece of code in the browser and node separately, you’ll get contradicting results.
In the browser, you will get:
However, in Node versions below 11.0.0, you’ll get the following output:
In Node JS implementation,
Promise callback is executed which resulted in the above output.
However, this contradicting output between the browser and Node has been under discussion for a while and a feature (or a fix) has been landed in Node.js v11.0.0 to follow the browser behavior. With this feature, Node.js v11.0.0 or above will output the following which matches the browser’s output:
See the following comparison between Node v10.15.1 and Node v11.10.0:
This change not only affects
setTimeout, but also affects
setImmediate. Let’s try to run the following code in Node v10 and Node v11 and see how the output is different.
Node v10 and Node v11 clearly give two different outputs as follows:
This behavior is quite the same if you replace
process.nextTick, because microtasks are run after the
process.nextTickcallbacks are run. Let’s try to run the following snippet:
The output of Node v10 and Node v11 for the above script is as follows:
What happens here?
With the new changes in Node v11,
nextTick callbacks and microtasks will run between each individual
setImmediate callbacks, even if the timers queue or the immediates queue is not empty. In terms of