Middle+
What are the scenarios for implementing the Event Loop in Node.js?
sobes.tech AI
Answer from AI
The Event Loop in Node.js operates in iterations (ticks) and processes the following phases:
- Timers: handles callbacks for
setTimeout()andsetInterval(). - Pending callbacks: executes callbacks for I/O operations deferred in the previous iteration.
- Idle, prepare: internal use of Node.js.
- Poll:
- Executes I/O callbacks (mostly).
- If no ready I/O callbacks, it may wait for new connections/events or transition to the Check phase.
- Check: executes callbacks for
setImmediate(). - Close callbacks: executes close event callbacks, e.g., for sockets (
'close').
Between main phases of the Event Loop, and after each phase, Node.js checks and executes the following microtask queues:
process.nextTick()queue: has the highest priority and executes before all other microtasks and Event Loop phases.- Promise queue: executes resolved promises.
Example:
// Executes before setTimeout, setImmediate, and I/O callbacks
process.nextTick(() => {
console.log('nextTick');
});
// Executes in the Timers phase
setTimeout(() => {
console.log('timeout');
}, 0);
// Executes in the Check phase
setImmediate(() => {
console.log('immediate');
});
// Example of an asynchronous I/O operation
const fs = require('fs');
fs.readFile(__filename, () => {
// Executes in the Poll phase
console.log('read file');
});
// Example of a promise
Promise.resolve().then(() => {
// Executes in the promise microtask queue
console.log('promise');
});
The output order in the console will be approximately:
nextTick
promise
timer
read file
immediate
(The order of 'read file' and 'immediate' may vary depending on the I/O operation execution).