Home >Web Front-end >Front-end Q&A >The node.js event queue has several stages

The node.js event queue has several stages

青灯夜游
青灯夜游Original
2021-12-09 17:55:152278browse

node.js event queue has 6 stages: 1. "timers" stage; 2. "I/O callbacks" stage; 3. "idle, prepare" stage; 4. "poll" stage; 5 , "check" stage; 6. "close callbacks" stage.

The node.js event queue has several stages

The operating environment of this tutorial: windows7 system, nodejs version 12.19.0, DELL G3 computer.

The event queue in Node is quite different from that in the browser, but the common point is that the mechanisms of macro tasks and micro tasks are the same, as shown in the figure about the macro tasks and micro tasks of node. Classification.
The node.js event queue has several stages
nexttick will be executed first (the highest priority of microtasks) when each event of the node is opened.

The node event queue can be divided into the following 6 stages:
The node.js event queue has several stages

1. Timers stage: This stage executes timer (setTimeout, setInterval ) callback

2. I/O callbacks stage: execute some system call errors, such as network communication error callback

3. idle, prepare stage: only used internally by node

4. Poll phase: Get new I/O events. Under appropriate conditions, node will block here.

5. Check phase: Execute the callback of setImmediate()

6. close callbacks stage: Execute the socket's close event callback

Let's focus on the three stages of timers, poll, and check, because most asynchronous tasks in daily development are processed in these three stages.

timers phase

timers is the first phase of the event loop. Node will check whether there is an expired timer, and if so, suppress its callback. Enter the timer's task queue to wait for execution. In fact, Node cannot guarantee that the timer will be executed immediately when the preset time is reached, because Node's expiration check of the timer is not necessarily reliable, and it will be affected by other running programs on the machine, or The main thread is not idle at that point in time. For example, in the following code, the execution order of setTimeout() and setImmediate() is uncertain.

setTimeout(() => {
  console.log('timeout')}, 0)setImmediate(() => {
  console.log('immediate')})

The above code is a big pitfall. Node cannot determine the specific time when the event queue is established each time. It may be 5ms this time (the timer is pushed onto the stack and will not be executed until the second round). Next time It is 1ms (timer is captured and executed in the first round). Therefore, the order of the output results is uncertain, which is also the specific reason. When an asynchronous operation is nested and wrapped, it is 100% guaranteed that the immediate will be executed first.

fs.readFile('./index.html',(err,result)=>{
	setTimeout(() => {
	  console.log('timeout')
	}, 0)
	
	setImmediate(() => {
	  console.log('immediate')
	})})

This is because the timer is not captured in the first round, so it goes directly to the poll stage to capture the io callback. When the io ends and enters the check stage, immediate will be executed, and timeout will be executed in the second round. The timer at the beginning of the round is executed.

poll phase

The poll phase mainly has two functions:
1. Process events in the poll queue
2. When there is a timer that has expired, Executing its callback function

even loop will synchronously execute the callbacks in the poll queue until the queue is empty or the executed callbacks reach the system upper limit (the upper limit is unknown), then the even loop will check whether there is a pre- There are two situations for setImmediate():

1. If there is a preset setImmediate(), the event loop will end the poll phase and enter the check phase, and execute the task queue of the check phase
2. If there is no preset setImmediate(), the event loop will be blocked in this stage and wait.

Note one detail. Without setImmediate(), the event loop will be blocked in the poll stage, so the timer set before will not be able to be executed. ? Therefore, during the poll phase, the event loop will have a checking mechanism to check whether the timer queue is empty. If the timer queue is not empty, the event loop will start the next round of event loop, that is, re-enter the timer phase.

check phase

The callback of setImmediate() will be added to the check queue. From the event loop phase diagram, we can know that the execution order of the check phase is after the poll phase. .

Summary

node Each large event loop is divided into six scenes, each Scenarios need to be executed in order, which is more detailed than the browser, and macro tasks and micro tasks are processed at each stage, which is a special point.

1. The event loop of Node.js is divided into 6 stages

2. The execution timing of the microtask task queue is different in the browser and Node environment

In Node.js, microtask is executed between various stages of the event loop

On the browser side, microtask is executed after the macrotask of the event loop is executed

3. Recursive call process .nextTick() will cause I/O starving. The official recommendation is to use setImmediate()

4. Nexttick has the highest priority among microtasks in each event stage.

For more node-related knowledge, please visit: nodejs tutorial! !

The above is the detailed content of The node.js event queue has several stages. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn