国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Asynchronous programming in JavaScript
JavaScript is synchronous
JavaScript is blocking
JavaScript is single-threaded
Waiting for JavaScript
Node.js Runtime
Libuv
Code execution in Node.js runtime
同步代碼執(zhí)行
異步代碼執(zhí)行
Libuv 和異步操作
What is the event loop?
Visualizing the event loop
How does the event loop work?
Conclusion
Home Web Front-end JS Tutorial Let's talk about the event loop in Node

Let's talk about the event loop in Node

Apr 11, 2023 pm 07:08 PM
javascript front end node.js

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

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 運行時中的執(zhí)行方式。在執(zhí)行代碼時,位于圖片左側(cè)的 V8 引擎負(fù)責(zé) JavaScript 代碼的執(zhí)行。該引擎包含一個內(nèi)存堆(Memory heap)和一個調(diào)用棧(Call stack)。

每當(dāng)聲明變量或函數(shù)時,都會在堆上分配內(nèi)存。執(zhí)行代碼時,函數(shù)就會被推入調(diào)用棧中。當(dāng)函數(shù)返回時,它就從調(diào)用棧中彈出了。這是對棧數(shù)據(jù)結(jié)構(gòu)的簡單實現(xiàn),最后添加的項是第一個被移除。在圖片右側(cè),是負(fù)責(zé)處理異步方法的 libuv。

每當(dāng)我們執(zhí)行異步方法時,libuv 接管任務(wù)的執(zhí)行。然后使用操作系統(tǒng)本地異步機制運行任務(wù)。如果本地機制不可用或不足,則利用其線程池來運行任務(wù),并確保主線程不被阻塞。

同步代碼執(zhí)行

首先,讓我們來看一下同步代碼執(zhí)行。以下代碼由三個控制臺日志語句組成,依次記錄“First”,“Second”和“Third”。我們按照運行時執(zhí)行順序來查看代碼。

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

以下是 Node 運行時執(zhí)行同步代碼的可視化展示。

Lets talk about the event loop in Node

執(zhí)行的主線程始終從全局作用域開始。全局函數(shù)(如果我們可以這樣稱呼它)被推入堆棧中。然后,在第 1 行,我們有一個控制臺日志語句。這個函數(shù)被推入堆棧中。假設(shè)這個發(fā)生在 1 毫秒時,“First” 被記錄在控制臺上。然后,這個函數(shù)從堆棧中彈出。

執(zhí)行到第 2 行時。假設(shè)到第 2 毫秒了,log 函數(shù)再次被推入堆棧中?!癝econd”被記錄在控制臺上,并彈出該函數(shù)。

最后,執(zhí)行到第 3 行了。第 3 毫秒時,log 函數(shù)被推入堆棧,“Third”將記錄在控制臺上,并彈出該函數(shù)。此時已經(jīng)沒有代碼要執(zhí)行,全局也被彈出。

異步代碼執(zhí)行

接下來,讓我們看一下異步代碼執(zhí)行。有以下代碼片段:包含三個日志語句,但這次第二個日志語句傳遞給了fs.readFile() 作為回調(diào)函數(shù)。

Lets talk about the event loop in Node

執(zhí)行的主線程始終從全局作用域開始。全局函數(shù)被推入堆棧。然后執(zhí)行到第 1 行,在第 1 毫秒時,“First”被記錄在控制臺中,并彈出該函數(shù)。然后執(zhí)行移動到第 2 行,在第 2毫秒時,readFile 方法被推入堆棧。由于 readFile 是異步操作,因此它會轉(zhuǎn)移(off-loaded)到 libuv。

JavaScript 從調(diào)用堆棧中彈出了 readFile 方法,因為就第 2 行的執(zhí)行而言,它的工作已經(jīng)完成了。在后臺,libuv 開始在單獨的線程上讀取文件內(nèi)容。在第 3 毫秒時,JavaScript 繼續(xù)進(jìn)行到第 5 行,將 log 函數(shù)推入堆棧,“Third”被記錄到控制臺中,并將該函數(shù)彈出堆棧。

大約在第 4 毫秒左右,假設(shè)文件讀取任務(wù)已經(jīng)完成,則相關(guān)回調(diào)函數(shù)現(xiàn)在會在調(diào)用棧上執(zhí)行, 在回調(diào)函數(shù)內(nèi)部遇到 log 函數(shù)。

log 函數(shù)推入到到調(diào)用棧,“Second”被記錄到控制臺并彈出 log 函數(shù) 。由于回調(diào)函數(shù)中沒有更多要執(zhí)行的語句,因此也被彈出 。沒有更多代碼可運行了 ,所以全局函數(shù)也從堆棧中刪除 。

控制臺輸出“First”,“Third”,然后是“Second”。

Libuv 和異步操作

很明顯,libuv 用于處理 Node.js 中的異步操作。對于像處理網(wǎng)絡(luò)請求這樣的異步操作,libuv 依賴于操作系統(tǒng)原生機制。對于沒有本地 OS 支持的異步讀取文件的操作,libuv 則依賴其線程池以確保主線程不被阻塞。然而,這也引發(fā)了一些問題。

  • 當(dāng)一個異步任務(wù)在 libuv 中完成時,什么時候 Node 會在調(diào)用棧上運行相關(guān)聯(lián)的回調(diào)函數(shù)?
  • Node 是否會等待調(diào)用棧為空后再運行回調(diào)函數(shù)?還是打斷正常執(zhí)行流來運行回調(diào)函數(shù)?
  • setTimeoutsetInterval 這類延遲執(zhí)行回調(diào)函數(shù)的方法又是何時執(zhí)行回調(diào)函數(shù)呢?
  • 如果 setTimeoutreadFile 這類異步任務(wù)同時完成,Node 如何決定哪個回調(diào)函數(shù)先在調(diào)用棧上運行?其中一個會有更多的優(yōu)先級嗎?

所有這些問題都可以通過理解 libuv 核心部分——事件循環(huán)來得到答案。

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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Combination of Golang and front-end technology: explore how Golang plays a role in the front-end field Combination of Golang and front-end technology: explore how Golang plays a role in the front-end field Mar 19, 2024 pm 06:15 PM

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn

See all articles