This article will take you to understand the event-loop (time loop) mechanism in Node.js. I hope it will be helpful to you!
Today we will learn about event-loop in nodeJs. The understanding of event-loop has always been a big difficulty for me. I hope to break through this difficulty through this study. I also hope to deepen my understanding and impression of event-loop through this blog.
Before learning event-loop, first understand the libuv of node. libuv is responsible for the implementation of different I/O models on different operating systems, and abstracts different implementations into APIs that can be used with third-party applications.
Before formally learning event-loop, let’s think about a question
setTimeout(() => { console.log("timer1"); Promise.resolve().then(() => { console.log("promise1"); }); }, 0); setTimeout(() => { console.log("timer2"); Promise.resolve().then(() => { console.log("promise2"); }); }, 0);
This code What is the result of running it in the browser?
What is the result of running it in node?
Before node8.6:
##After node8.6:
Under appropriate circumstances, nodejs will block in this phase
FIFO(First in first out) rule to execute the task queue tasks inside. Among these six stages, we focus on the timers, poll, check stages. Most of the asynchronous tasks in our daily development are handled in these three stages.
Timers is the first stage of the event loop. Nodejs will check whether there is an expired timer, and if so, put its callback into the queue. However, nodejs cannot guarantee that the timer will execute the callback immediately when the preset event arrives. This is because the expiration check of the timer by nodejs is not necessarily reliable. It will be affected by other running programs on the machine, or it will encounter the current main thread. Not idle situation. Regarding the uncertainty here, the official website gives an example:
First declare a setTimeOut, and then read a file externally. When the file reading operation exceeds the timer time, in this way, the read File operations will delay the timer's callback. This is the situation where the main thread is not idle as mentioned earlier.
After executing the poll task queue in the poll phase After the task, it will check whether there is a preset setImmediate. If there is, it will enter the check phase. If not, nodejs will block here.
Here we will have a question. If it is blocked in the poll stage, wouldn't the timer we set cannot be executed?In fact
When the event-loop is blocked in the poll phase, nodejs will have a checking mechanism. It will check whether the timers queue is empty. If it is not empty, it will re-enter the timers phase.
event-loop的每个阶段都有一个队列,当event-loop达到某个阶段之后,将执行这个阶段的任务队列,直到队列清空或者达到系统规定的最大回调限制之后,才会进入下一个阶段。当所有阶段都执行完成一次之后,称event-loop完成一个tick。
上面我们说完了event-loop的理论部分,但是光有理论我们也还是不能很清晰的理解event-loop。下面我们就根据几个demo来更加深入的理解下event-loop!
demo1
const fs=require('fs') fs.readFile('test.txt',()=>{ console.log('readFile') setTimeout(()=>{ console.log('settimeout'); },0) setImmediate(()=>{ console.log('setImmediate') }) })
执行结果:
可见执行结果跟我们前面的分析时一致的!
demo2
const fs = require("fs"); const EventEmitter = require("events").EventEmitter; let pos = 0; const messenger = new EventEmitter(); messenger.on("message", function (msg) { console.log(++pos + " message:" + msg); // }); console.log(++pos + " first"); // process.nextTick(function () { console.log(++pos + " nextTick"); // }); messenger.emit("message", "hello!"); fs.stat(__filename, function () { console.log(++pos + " stat"); // }); setTimeout(function () { console.log(++pos + " quick timer"); // }, 0); setTimeout(function () { console.log(++pos + " long timer"); // }, 30); setImmediate(function () { console.log(++pos + " immediate"); // }); console.log(++pos + " last"); //
结果:
在node 8.6 之前:
浏览器中的微任务队列会在每个宏任务执行完成之后执行,而node中的微任务会在事件循环的各个阶段之间执行,即每个阶段执行完成之后会去执行微任务队列。
在8.6之后:
浏览器和node中微任务的执行是一致的!
所以,在文章开头,我们提出的思考的问题就有了结果。
语法:process.nextTick(callback,agrs)
执行时机:
这个函数其实是独立于 Event Loop 之外的,它有一个自己的队列,当每个阶段完成后,如果存在 nextTick 队列,就会清空队列中的所有回调函数,并且优先于其他 microtask 执行。递归的调用process.nextTick()
会导致I/O starving,官方推荐使用setImmediate()
关于starving现象的说明:
const fs = require("fs"); fs.readFile("test.txt", (err, msg) => { console.log("readFile"); }); let index = 0; function handler() { if (index >= 30) return; index++; console.log("nextTick" + index); process.nextTick(handler); } handler();
运行结果:
可以看到,等到nextTick函数呗执行30次之后,读取文件的回调才被执行!这样的现象被称为 I/O 饥饿。
当我们把 process.nextTick 换为 setImmediate
const fs = require("fs"); fs.readFile("test.txt", (err, msg) => { console.log("readFile"); }); let index = 0; function handler() { if (index >= 30) return; index++; console.log("nextTick" + index); setImmediate(handler); } handler();
结果:
造成这两种差异的原因是,嵌套调用的setImmediate的回调被排到了下一次event-loop中去!
通过今天的学习,让我对event-loop的理解更深刻了。那么,下次见。好好学习,天天向上!
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of An article to talk about the event-loop mechanism in Node.js. For more information, please follow other related articles on the PHP Chinese website!