We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Understanding Async Context - James Snell, Node Congress 2024
Learn how to seamlessly store and retrieve values across promises in your Node.js applications with AsyncLocalStorage, a centralized storage mechanism built on top ofExecutionContext and async_hooks APIs.
- AsyncLocalStorage is a centralized storage mechanism for Node.js, allowing to store and retrieve values across promises.
-
It is built on top of the
ExecutionContext
API and uses theasync_hooks
module. - When a promise is created, a new frame is created, which is a copy of the current frame.
-
The frame is immutable and is reset to a new instance every time
ALS run
is called. -
The
runtime
storage frame is used to store the current frame, which is used to retrieve the current value of an async local storage instance. - AsyncLocalStorage uses a copy-on-write strategy to avoid modifying the original frame.
-
The
async local storage
instance itself is a map that stores key-value pairs. - When a new value is set, a new frame is created with a copy of the current frame and the new value.
-
Each call to
ALS run
sets the current frame to the new frame. - When a task is run, its captured frame is temporarily set as the current frame.
-
The
async local storage
instance can be used to store and retrieve values across promises. - AsyncLocalStorage is a drop-in replacement for existing code, and will work with most promise chains.
-
The
async local storage
instance uses a map to store key-value pairs. -
The initial frame is empty, and each call to
ALS run
creates a new frame and sets it as the current frame. -
The
async local storage
instance uses a copy-on-write strategy to avoid modifying the original frame. - When a promise is created, a new task is created that captures a reference to the current frame.