Home>Article>Web Front-end> This article will take you to understand the eventloop in Node.js

This article will take you to understand the eventloop in Node.js

青灯夜游
青灯夜游 forward
2022-01-04 18:44:13 2246browse

The main thread reads events from the "task queue". This process is cyclic, so the entire running mechanism is also called Event Loop. The following article will help you master the eventloop inNode.js. I hope it will be helpful to you!

This article will take you to understand the eventloop in Node.js

#In fact, I also talked about the eventloop in the browser in the previous article. However, the eventloop in NodeJs is different from that in the browser. Mastering eventloop is a very important skill for people who writenodejs. Because this means that you can not only write js, but also study NodeJs.

Why is there an eventloop?

We know that the essence of NodeJs is to move the browser's v8 to run in the operating system, so it also takes over the browser's event loop. But why does a design like eventloop appear?

From a historical perspective, js was designed as a very simple language for operating dom on the page (I believe everyone has heard the story that js was designed in only 10 days). For this goal, we certainly hope that the execution of js will be as simple and lightweight as possible. How lightweight can it be? The rendering engine as light as js runs in a thread.

Then the problem comes. If js is run on a thread, when the code is linear, of course there is no problem. But on the page, we need user interactions, and these interactions don't know why and when they happen. How to deal with js? If there is running code in front of you, how should the program react when a user interacts? If the user interaction is processed first, the original program will be suspended (that is, blocked). In order to avoid this kind of blocking, js adopts a method, which is to use a message queue to store this kind of user interaction. After all the programs have finished running, go to the message queue to get the interaction event, and then execute it. This solves the blocking problem.

Browser eventloop

We all know that when the browser is browsing the page, user interaction may occur at any time, in order to respond to the user immediately. js will not be closed, it will keep looping. It is roughly as follows:

向消息队列拿任务-->执行任务-->执行完毕--> 向消息队列拿任务--> ....

Of course, we have mentioned in the previous event loop article that in order to classify different asynchronous tasks, there is actually a distinction between macro tasks and micro tasks in the event loop. Their execution is roughly

向消息队列拿微任务-->执行微任务-->微任务执行完毕--> 向消息队列拿宏任务-->执行宏任务-->宏任务执行完毕-->向消息队列拿微任务-->...

NodeJs's eventloop

node's event loop is actually similar to that on the browser. However, nodeJs distinguishes different macro tasks at different times. The following is the official flow chart:

This article will take you to understand the eventloop in Node.js

You can see that each event loop in nodeJs is divided into 6 specific periods, and each period will use designated macro tasks. Then before the macro tasks of each period are executed, the micro task queue will be executed first.

Overview

其实通过上述表格,我们已经很清晰知道整个事件循环机制的执行顺序了。但可能大家还会有一些疑问。下面来详细讲一下。

pending callbacks

这个阶段其实是处理由于操作系统出错,导致一些本应在上次事件循环中执行的回调。例如一些TCP错误。因此这部分,开发者不能主动操作,是NodeJs的一些容错机制。

check

同样的,setImmediate是nodejs特有的api,他可以立即创建一个异步宏任务。不仅如此,nodejs在事件循环中还专门设了一个check时期,在这个时期会专门执行setImmediate的回调。甚至你可以在这个时期中如果不停的产生setImmediate回调,eventloop会优先处理。

close callbacks

这个时期处理关闭事件,如socket.on('close', ...)等这样可以确保在一些通讯结束前,所有任务都完成了。

微任务在eventloop中

我们先来回顾浏览器与nodejs的差异:

宏任务:

Execution is delayed until I/O callbacks for the next loop iteration are only used internally, developers may not pay attention Retrieve new I/O events; execute I/O related callbacks (almost all callbacks will be executed except close callbacks and timers scheduling The callbacks and callbacks scheduled by setImmediate() will block at this stage at the appropriate time) Execution For example
timers Executed bysetTimeout()andsetInterval()Triggered callbacks
##pending callbacks
idle, prepare
poll
checksetImmediate()
close callbackssocket.on('close', ...)
任务 浏览器 Node
I/O
setTimeout
setInterval
setImmediate
requestAnimationFrame

微任务:

任务 浏览器 Node
process.nextTick
MutationObserver
Promise.then catch finally

可以看到process.nextTick是nodejs特有的微任务,不仅如此,process.nextTick()的优先级高于所有的微任务,每一次清空微任务列表的时候,都是先执行 process.nextTick()

执行差异

不仅是任务类型上有差异,在执行上2个环境其实也有差异。在浏览器上执行任务的时候,每执行一个宏任务之前,需要先确保微任务队列执行完了。而在nodejs上是每个时期之前,先确保微任务队列执行完。也就是说在假如在timer时期,会先把所有setTimeout,setInterval的宏任务执行完。在执行完微任务,再进入下个时期。

注意:以上执行规则是在nodejs的v11版本之前的规则。在11版本之后nodejs的执行输出是跟浏览器一样的。

setImmediate() vs setTimeout()

setImmediate() 和 setTimeout()的执行先后顺序是不一定的,就是说如果你不停地执行以下代码,每次得到的结果可能是不一样的。

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

其中的原因是程序对时间的处理是有误差的。在setTimeout方法中设置的时间,不一定是准确的。同时在回调触发时,也无法确认事件循环处在哪个时期,可能是timer,也可能是check。所有会有不同的结果。

总结

eventloop是js运行机制里的重点内容,对于NodeJs来说,eventloop的操作空间则更大。因为它被细分为不同的时期,从而让我们可能把逻辑进一步细化。同时利用nextTick的最高优先级,可以写出在浏览器无法实现的代码。因此对于深入NodeJs的开发者来说,eventloop往往是他们考察新人对NodeJs理解的第一步。

更多node相关知识,请访问:nodejs 教程!!

The above is the detailed content of This article will take you to understand the eventloop in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete