Home >Web Front-end >JS Tutorial >An article to talk about the event-loop mechanism in Node.js

An article to talk about the event-loop mechanism in Node.js

青灯夜游
青灯夜游forward
2021-11-05 09:48:252375browse

This article will take you to understand the event-loop (time loop) mechanism in Node.js. I hope it will be helpful to you!

An article to talk about the event-loop mechanism in Node.js

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.

libuv

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.

An article to talk about the event-loop mechanism in Node.js

Question

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?

An article to talk about the event-loop mechanism in Node.js

What is the result of running it in node?

Before node8.6:

An article to talk about the event-loop mechanism in Node.js

##After node8.6:

An article to talk about the event-loop mechanism in Node.js

Why there is such a result, we will analyze it later!

event-loop in nodeJs

First of all, Let’s look at a picture:

An article to talk about the event-loop mechanism in Node.js

#You can see 6 stages in the picture, namely: timers, pending callbacks, idle/prepare, poll, check, close callbacks.

  • timers phase: mainly execute setTimeOut, setInterval callbacks

  • pending callbacks phase: execute some system call errors, such as network communication Error callback

  • idle/prepare phase: only used within the system (we cannot control and interfere with this phase)

  • poll phase: get new I/O events, such as getting an I/O callback for reading a file.

    Under appropriate circumstances, nodejs will block in this phase

  • check phase: execute setImmediate callback

  • For example Execute the destroy and close event callbacks of sokect

Each stage follows a

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

Let’s talk about the timers stage first.


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.

poll

The poll phase mainly performs two things:

1. Process the task queue of the poll phase

2. When there is a timer that has timed out, its callback function is executed

An article to talk about the event-loop mechanism in Node.js

In the above figure, we can also see:

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.

check

The check phase mainly executes the setImmediate callback function.

小总结

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')
            })
    })

执行结果:

An article to talk about the event-loop mechanism in Node.js

可见执行结果跟我们前面的分析时一致的!

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"); //

结果:

An article to talk about the event-loop mechanism in Node.js

了解下浏览器和node的event-loop差异在什么地方

在node 8.6 之前:

浏览器中的微任务队列会在每个宏任务执行完成之后执行,而node中的微任务会在事件循环的各个阶段之间执行,即每个阶段执行完成之后会去执行微任务队列。

在8.6之后:

浏览器和node中微任务的执行是一致的!

所以,在文章开头,我们提出的思考的问题就有了结果。

关于 process.nextTick()和setImmediate

process.nextTick()

语法: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();

运行结果:

An article to talk about the event-loop mechanism in Node.js

可以看到,等到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();

结果:

An article to talk about the event-loop mechanism in Node.js

造成这两种差异的原因是,嵌套调用的setImmediate的回调被排到了下一次event-loop中去!

event-loop核心思维导图

1An article to talk about the event-loop mechanism in Node.js

结束语

通过今天的学习,让我对event-loop的理解更深刻了。那么,下次见。好好学习,天天向上!

1An article to talk about the event-loop mechanism in Node.js

更多编程相关知识,请访问:编程视频!!

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!

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