Home > Web Front-end > JS Tutorial > body text

Let's talk about the event loop in Node

青灯夜游
Release: 2023-04-11 19:08:21
forward
1428 people have browsed it

The event loop is a fundamental part of Node.js. It enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

Lets talk about the event loop in Node

You've been using Node.js for a while, built a few apps, tried out different modules, and even feel comfortable with asynchronous programming. But something keeps bothering you - the event loop.

If you are like me, you have spent countless hours reading documentation and watching videos trying to understand the event loop. But even as an experienced developer, you may have trouble fully understanding how it works. That’s why I’ve prepared this visual guide to help you fully understand the Node.js event loop. So sit back, grab a cup of coffee, and let’s dive into the world of the Node.js event loop. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]

Asynchronous programming in JavaScript

We will start from A review of asynchronous programming in JavaScript begins. While JavaScript is used in web, mobile, and desktop applications, it's important to remember that, at its core, JavaScript is a synchronous, blocking, single-threaded language. Let us understand this sentence through a short code snippet.

// index.js

function A() {
  console.log("A");
}

function B() {
  console.log("B");
}

A()
B()

// Logs A and then B
Copy after login

JavaScript is synchronous

If we have two functions that log messages to the console, then the code will be executed from top to bottom, only executing each time One line. In the above code snippet, we see that A is recorded before B.

JavaScript is blocking

JavaScript is blocking due to its synchronous nature. No matter how long the previous process takes, subsequent processes will not start until the former completes. In the code snippet, if function A has to execute a large block of code, JavaScript has to complete that operation without branching to function B. Even if this piece of code takes 10 seconds or even a minute.

You may have encountered this situation in your browser. When a web application is running in the browser and executes some intensive blocks of code without returning control to the browser, the browser may freeze, which is called blocking. The browser is blocked from continuing to process user input and perform other tasks until the web application returns processor control to the browser.

JavaScript is single-threaded

A thread is the process that your JavaScript program can use to run tasks. Each thread can only perform one task at a time. Unlike other languages ​​that support multi-threading and can run multiple tasks simultaneously, JavaScript has only one thread called the main thread that executes code.

Waiting for JavaScript

As you can imagine, this JavaScript model creates problems because we have to wait for the data to be fetched before we can continue executing the code. This wait may take several seconds, during which we cannot run any other code. If JavaScript continues processing without waiting, an error occurs. We need to implement asynchronous behavior in JavaScript. Let's go into Node.js and take a look.

Node.js Runtime

Lets talk about the event loop in Node

The Node.js runtime is an environment that you can use without using a browser Use and run JavaScript programs. Core - the Node runtime, consists of three main components.

  • External dependencies — such as V8, libuv, crypto, etc. — are required features of Node.js
  • C features provide functionality such as file system access and networking.
  • The JavaScript library provides functions and tools to facilitate calling C features using JavaScript code.

While all parts are important, the key component of asynchronous programming in Node.js is libuv.

Libuv

Libuv is a cross-platform open source library written in C language. In the Node.js runtime, its role is to provide support for handling asynchronous operations. Let's take a look at how it works.

Code execution in Node.js runtime

Lets talk about the event loop in Node

让我们来概括一下代码在 Node 运行时中的执行方式。在执行代码时,位于图片左侧的 V8 引擎负责 JavaScript 代码的执行。该引擎包含一个内存堆(Memory heap)和一个调用栈(Call stack)。

每当声明变量或函数时,都会在堆上分配内存。执行代码时,函数就会被推入调用栈中。当函数返回时,它就从调用栈中弹出了。这是对栈数据结构的简单实现,最后添加的项是第一个被移除。在图片右侧,是负责处理异步方法的 libuv。

每当我们执行异步方法时,libuv 接管任务的执行。然后使用操作系统本地异步机制运行任务。如果本地机制不可用或不足,则利用其线程池来运行任务,并确保主线程不被阻塞。

同步代码执行

首先,让我们来看一下同步代码执行。以下代码由三个控制台日志语句组成,依次记录“First”,“Second”和“Third”。我们按照运行时执行顺序来查看代码。

// index.js
console.log("First");
console.log("Second");
console.log("Third");
Copy after login

以下是 Node 运行时执行同步代码的可视化展示。

Lets talk about the event loop in Node

执行的主线程始终从全局作用域开始。全局函数(如果我们可以这样称呼它)被推入堆栈中。然后,在第 1 行,我们有一个控制台日志语句。这个函数被推入堆栈中。假设这个发生在 1 毫秒时,“First” 被记录在控制台上。然后,这个函数从堆栈中弹出。

执行到第 2 行时。假设到第 2 毫秒了,log 函数再次被推入堆栈中。“Second”被记录在控制台上,并弹出该函数。

最后,执行到第 3 行了。第 3 毫秒时,log 函数被推入堆栈,“Third”将记录在控制台上,并弹出该函数。此时已经没有代码要执行,全局也被弹出。

异步代码执行

接下来,让我们看一下异步代码执行。有以下代码片段:包含三个日志语句,但这次第二个日志语句传递给了fs.readFile() 作为回调函数。

Lets talk about the event loop in Node

执行的主线程始终从全局作用域开始。全局函数被推入堆栈。然后执行到第 1 行,在第 1 毫秒时,“First”被记录在控制台中,并弹出该函数。然后执行移动到第 2 行,在第 2毫秒时,readFile 方法被推入堆栈。由于 readFile 是异步操作,因此它会转移(off-loaded)到 libuv。

JavaScript 从调用堆栈中弹出了 readFile 方法,因为就第 2 行的执行而言,它的工作已经完成了。在后台,libuv 开始在单独的线程上读取文件内容。在第 3 毫秒时,JavaScript 继续进行到第 5 行,将 log 函数推入堆栈,“Third”被记录到控制台中,并将该函数弹出堆栈。

大约在第 4 毫秒左右,假设文件读取任务已经完成,则相关回调函数现在会在调用栈上执行, 在回调函数内部遇到 log 函数。

log 函数推入到到调用栈,“Second”被记录到控制台并弹出 log 函数 。由于回调函数中没有更多要执行的语句,因此也被弹出 。没有更多代码可运行了 ,所以全局函数也从堆栈中删除 。

控制台输出“First”,“Third”,然后是“Second”。

Libuv 和异步操作

很明显,libuv 用于处理 Node.js 中的异步操作。对于像处理网络请求这样的异步操作,libuv 依赖于操作系统原生机制。对于没有本地 OS 支持的异步读取文件的操作,libuv 则依赖其线程池以确保主线程不被阻塞。然而,这也引发了一些问题。

  • 当一个异步任务在 libuv 中完成时,什么时候 Node 会在调用栈上运行相关联的回调函数?
  • Node 是否会等待调用栈为空后再运行回调函数?还是打断正常执行流来运行回调函数?
  • setTimeoutsetInterval 这类延迟执行回调函数的方法又是何时执行回调函数呢?
  • 如果 setTimeoutreadFile 这类异步任务同时完成,Node 如何决定哪个回调函数先在调用栈上运行?其中一个会有更多的优先级吗?

所有这些问题都可以通过理解 libuv 核心部分——事件循环来得到答案。

What is the event loop?

Technically speaking, the event loop is just a C language program. But in Node.js, you can think of it as a design pattern for coordinating the execution of synchronous and asynchronous code.

Visualizing the event loop

The event loop is a loop that runs as long as your Node.js application is running. There are six different queues in each loop, each containing one or more callback functions that need to eventually be executed on the call stack.

Lets talk about the event loop in Node

  • First, there is a timer queue (timer queue. Technically called min-heap), which saves the same number as setTimeout Callback functions related to setInterval.
  • Secondly, there is an I/O queue (I/O queue), which contains callback functions related to all asynchronous methods, such as fs and http modules related methods provided.
  • The third one is the check queue, which holds the callback function related to the setImmediate function, which is a Node-specific function.
  • The fourth is the close queue (close queue), which saves the callback function associated with the asynchronous task closing event.

Finally, there are two different queues forming the microtask queue.

  • nextTick queue stores the callback function associated with the process.nextTick function.
  • The Promise queue stores the callback functions associated with local Promise in JavaScript.

It should be noted that timers, I/O, check and close queues all belong to libuv. However, the two microtask queues do not belong to libuv. Nonetheless, they still play an important role in the Node runtime environment and play an important role in the order in which callbacks are executed. Having said that, let’s understand how the event loop works.

How does the event loop work?

The arrow in the picture is a hint, but it may not be easy to understand. Let me explain the queue priority order. The first thing to know is that all user-written synchronous JavaScript code takes precedence over asynchronous code. This means that the event loop only functions when the call stack is empty.

In the event loop, the order of execution follows certain rules. There are still some rules that need to be mastered. Let’s take a look at them one by one:

  1. Execute all callback functions in the microtask queue. First the tasks in the nextTick queue, then the tasks in the Promise queue.
  2. Execute all callback functions in the timer queue.
  3. If there is a callback function in the microtask queue, all callback functions in the microtask queue will be executed after each callback function is executed in the timer queue. First the tasks in the nextTick queue, then the tasks in the Promise queue.
  4. Execute all callback functions in the I/O queue.
  5. If there are callback functions in the microtask queue, all callback functions in the microtask queue will be executed sequentially in the order of nextTick queue and then Promise queue.
  6. Execute all callback functions in the check queue.
  7. If there is a callback function in the microtask queue, all callback functions in the microtask queue will be executed after checking each callback in the queue. First the tasks in the nextTick queue, then the tasks in the Promise queue.
  8. Execute all callback functions in the close queue.
  9. At the end of the same loop, execute the microtask queue again. First the tasks in the nextTick queue, then the tasks in the Promise queue.

At this time, if there are more callbacks to be processed, the event loop runs again (Annotation: The event loop keeps running while the program is running, and there are currently no tasks to process. Next, it will be in a waiting state and will be executed as soon as there is a new task), and repeat the same steps. On the other hand, if all callbacks have been executed and there is no more code to process, the event loop exits.

This is what the libuv event loop does for executing asynchronous code in Node.js. With these rules in hand, we can revisit the questions we asked earlier.


When an asynchronous task completes in libuv, when will Node run the associated callback function on the call stack?

Answer: The callback function is only executed when the call stack is empty.

Will Node wait for the call stack to be empty before running the callback function? Or interrupt the normal execution flow to run the callback function?

Answer: Running the callback function will not interrupt the normal execution flow.

Methods like setTimeout and setInterval that delay the execution of callback functions, when do they execute the callback function?

Answer: The first priority among all callback functions of setTimeout and setInterval is executed (regardless of the microtask queue).

If two asynchronous tasks (such as setTimeout and readFile) complete at the same time, how does Node decide which callback function to execute first in the call stack? ? Will one have higher priority than the other?

Answer: In the case of simultaneous completion, the timer callback will be executed before the I/O callback.


We have learned a lot so far, but I hope you can keep the execution sequence shown in the picture below in mind, because it completely shows what Node.js does behind the scenes. How to execute asynchronous code.

Lets talk about the event loop in Node

But, you may ask: "Where is the code to verify this visualization?". Well, each queue in the event loop has implementation nuances, so we'd better talk about them one by one. This article is the first in a series about the Node.js event loop. Please be sure to check the link at the end of the article to understand the details of the operation in each queue. Even if you have a deep impression in your mind now, you may still fall into some traps when you get to the specific scenario.

Conclusion

This visual guide covers the basics of asynchronous programming in JavaScript, the Node.js runtime, and libuv, which is responsible for handling asynchronous operations. With this knowledge, you can build a powerful event loop model that will benefit when writing code that takes advantage of the asynchronous nature of Node.js.

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

The above is the detailed content of Let's talk about the event loop in Node. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!