


What are asynchronous resources? A brief analysis of Node's method of realizing asynchronous resource context sharing
How does Node.js implement asynchronous resource context sharing? The following article will introduce to you how Node implements asynchronous resource context sharing. Let’s talk about the use of asynchronous resource context sharing for us. I hope it will be helpful to everyone!
Asynchronous resource context sharing means sharing context data within a network request life cycle or asynchronous resource call chain.
Before answering this question, we must first understand what asynchronous resources are.
Asynchronous resources
Asynchronous resources can be understood as objects with callbacks, such as but not limited to Promises, Timeouts, TCPWrap, UDP, etc. See Asynchronous resource type list for details.
The official definition is as follows:
An asynchronous resource represents an object with an associated callback. This callback may be called multiple times, such as the 'connection' event in net.createServer( ), or just a single time like in fs.open(). A resource can also be closed before the callback is called.
AsyncLocalStorage
here Introducing Node.js AsyncLocalStorage, the officially provided asynchronous context sharing solution. This feature was still an experimental feature before 16.4.0 and has been stable since 16.4.0.
AsyncLocalStorage can share data in asynchronous operation chains.
AsyncLocalStorage instance asyncLocalStorage has the following main methods:
- disable() disables asyncLocalStorage;
- getStore() returns the current context store, which must pass asyncLocalStorage .run() or asyncLocalStorage.enterWith() to perform asynchronous context initialization;
- enterWith(store) passes the context store through this method, and the store can be obtained in all subsequent asynchronous calls;
Example:
const store = { id: 1 }; // Replaces previous store with the given store object asyncLocalStorage.enterWith(store); asyncLocalStorage.getStore(); // Returns the store object someAsyncOperation(() => { asyncLocalStorage.getStore(); // Returns the same object });
- run(store, callback[, ...args]) Use run to specify the context store and its effective callback function. The store will only be in is obtained from the callback function.
- exit(callback[, ...args])
asyncLocalStorage.run() The first parameter of the function is to store the shared data we need to access in the asynchronous call. The second parameter is an asynchronous function.
The following is an example to demonstrate how to use AsyncLocalStorage to implement asynchronous resource context sharing:
Output:
runA 8f19ebef-58d7-4b1a-8b9b-46d158beb5d2 2022/5/24 20:26:17 this is a log message runB 8f19ebef-58d7-4b1a-8b9b-46d158beb5d2 2022/5/24 20:26:17 this is a log message
Through asyncLocalStorage.run In the same asynchronous function running, function runA and function runB will be run, and runA and runB can access the same context data.
Performance issues
AsyncLocalStorage provides a large traversal for us to easily implement asynchronous resource context sharing in Node.js, but every asynchronous resource operation will trigger Async Hooks , will inevitably have a certain impact on the performance of our Node application. So how big is the impact?
According to an actual measurement by Kuzzle, using AsyncLocalStorage will cause about 8% additional performance loss. Of course, different business scenarios may have different performance. If you are concerned about this part of performance, you can also add comparative testing to your business to test the specific performance impact.
---- | Log with AsyncLocalStorage | Log classic | difference |
---|---|---|---|
req/s | 2613 | 2842 | ~8% |
Application Scenario
In other multi-threaded languages, each HTTP creates a new thread, and each thread has its own memory. You can store global state in thread memory and retrieve global state from anywhere in your code.
In Node.js, because Node.js is single-threaded and shares memory among all HTTP requests, each HTTP request cannot hold mutually isolated global state.
AsyncLocalStorage can effectively isolate the status between different asynchronous operations, and plays a very important role in scenarios such as HTTP request tracking, APM tools, context log tracking, and request-based full-link log tracking.
For more node-related knowledge, please visit: nodejs tutorial!
The above is the detailed content of What are asynchronous resources? A brief analysis of Node's method of realizing asynchronous resource context sharing. For more information, please follow other related articles on the PHP Chinese website!

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
