Asynchronous context tracking | Node.js v22.23.2 Documentation
https://nodejs.org/docs/latest-v22.x/api/async_context.html • 86 KB fetched
Open original page
Asynchronous context tracking | Node.js v22.23.2 Documentation
Skip to content
Node.js
* About this documentation
* Usage and example
* Assertion testing
* Asynchronous context tracking
* Async hooks
* Buffer
* C++ addons
* C/C++ addons with Node-API
* C++ embedder API
* Child processes
* Cluster
* Command-line options
* Console
* Crypto
* Debugger
* Deprecated APIs
* Diagnostics Channel
* DNS
* Domain
* Environment Variables
* Errors
* Events
* File system
* Globals
* HTTP
* HTTP/2
* HTTPS
* Inspector
* Internationalization
* Modules: CommonJS modules
* Modules: ECMAScript modules
* Modules: node:module API
* Modules: Packages
* Modules: TypeScript
* Net
* OS
* Path
* Performance hooks
* Permissions
* Process
* Punycode
* Query strings
* Readline
* REPL
* Report
* Single executable applications
* SQLite
* Stream
* String decoder
* Test runner
* Timers
* TLS/SSL
* Trace events
* TTY
* UDP/datagram
* URL
* Utilities
* V8
* VM
* WASI
* Web Crypto API
* Web Streams API
* Worker threads
* Zlib
* Code repository and issue tracker
Node.js v22.23.2 documentation
* Node.js v22.23.2
*
Table of contents
* Asynchronous context tracking
* Introduction
* Class: AsyncLocalStorage
* new AsyncLocalStorage()
* Static method: AsyncLocalStorage.bind(fn)
* Static method: AsyncLocalStorage.snapshot()
* asyncLocalStorage.disable()
* asyncLocalStorage.getStore()
* asyncLocalStorage.enterWith(store)
* asyncLocalStorage.run(store, callback[, ...args])
* asyncLocalStorage.exit(callback[, ...args])
* Usage with async/await
* Troubleshooting: Context loss
* Class: AsyncResource
* new AsyncResource(type[, options])
* Static method: AsyncResource.bind(fn[, type[, thisArg]])
* asyncResource.bind(fn[, thisArg])
* asyncResource.runInAsyncScope(fn[, thisArg, ...args])
* asyncResource.emitDestroy()
* asyncResource.asyncId()
* asyncResource.triggerAsyncId()
* Using AsyncResource for a Worker thread pool
* Integrating AsyncResource with EventEmitter
*
Index
* About this documentation
* Usage and example
*
Index
* Assertion testing
* Asynchronous context tracking
* Async hooks
* Buffer
* C++ addons
* C/C++ addons with Node-API
* C++ embedder API
* Child processes
* Cluster
* Command-line options
* Console
* Crypto
* Debugger
* Deprecated APIs
* Diagnostics Channel
* DNS
* Domain
* Environment Variables
* Errors
* Events
* File system
* Globals
* HTTP
* HTTP/2
* HTTPS
* Inspector
* Internationalization
* Modules: CommonJS modules
* Modules: ECMAScript modules
* Modules: node:module API
* Modules: Packages
* Modules: TypeScript
* Net
* OS
* Path
* Performance hooks
* Permissions
* Process
* Punycode
* Query strings
* Readline
* REPL
* Report
* Single executable applications
* SQLite
* Stream
* String decoder
* Test runner
* Timers
* TLS/SSL
* Trace events
* TTY
* UDP/datagram
* URL
* Utilities
* V8
* VM
* WASI
* Web Crypto API
* Web Streams API
* Worker threads
* Zlib
* Code repository and issue tracker
*
Other versions
* 26.x
* 25.x
* 24.x LTS
* 23.x
* 22.x LTS
* 21.x
* 20.x
* 19.x
* 18.x
* 17.x
* 16.x
*
Options
*
View on single page
*
View as JSON
* Edit on GitHub
Table of contents
* Asynchronous context tracking
* Introduction
* Class: AsyncLocalStorage
* new AsyncLocalStorage()
* Static method: AsyncLocalStorage.bind(fn)
* Static method: AsyncLocalStorage.snapshot()
* asyncLocalStorage.disable()
* asyncLocalStorage.getStore()
* asyncLocalStorage.enterWith(store)
* asyncLocalStorage.run(store, callback[, ...args])
* asyncLocalStorage.exit(callback[, ...args])
* Usage with async/await
* Troubleshooting: Context loss
* Class: AsyncResource
* new AsyncResource(type[, options])
* Static method: AsyncResource.bind(fn[, type[, thisArg]])
* asyncResource.bind(fn[, thisArg])
* asyncResource.runInAsyncScope(fn[, thisArg, ...args])
* asyncResource.emitDestroy()
* asyncResource.asyncId()
* asyncResource.triggerAsyncId()
* Using AsyncResource for a Worker thread pool
* Integrating AsyncResource with EventEmitter
Asynchronous context tracking #
Stability: 2 - Stable
Source Code: lib/async_hooks.js
Introduction #
These classes are used to associate state and propagate it throughout
callbacks and promise chains.
They allow storing data throughout the lifetime of a web request
or any other asynchronous duration. It is similar to thread-local storage
in other languages.
The AsyncLocalStorage and AsyncResource classes are part of the
node:async_hooks module:
import { AsyncLocalStorage , AsyncResource } from 'node:async_hooks' ; const { AsyncLocalStorage , AsyncResource } = require ( 'node:async_hooks' ); copy
Class: AsyncLocalStorage #
History
Version Changes
v16.4.0
AsyncLocalStorage is now Stable. Previously, it had been Experimental.
v13.10.0, v12.17.0
Added in: v13.10.0, v12.17.0
This class creates stores that stay coherent through asynchronous operations.
While you can create your own implementation on top of the node:async_hooks
module, AsyncLocalStorage should be preferred as it is a performant and memory
safe implementation that involves significant optimizations that are non-obvious
to implement.
The following example uses AsyncLocalStorage to build a simple logger
that assigns IDs to incoming HTTP requests and includes them in messages
logged within each request.
import http from 'node:http' ;
import { AsyncLocalStorage } from 'node:async_hooks' ;
const asyncLocalStorage = new AsyncLocalStorage ();
function logWithId ( msg ) {
const id = asyncLocalStorage. getStore ();
console . log ( ` ${id !== undefined ? id : '-' } :` , msg);
}
let idSeq = 0 ;
http. createServer ( ( req, res ) => {
asyncLocalStorage. run (idSeq++, () => {
logWithId ( 'start' );
// Imagine any chain of async operations here
setImmediate ( () => {
logWithId ( 'finish' );
res. end ();
});
});
}). listen ( 8080 );
http. get ( 'http://localhost:8080' );
http. get ( 'http://localhost:8080' );
// Prints:
// 0: start
// 0: finish
// 1: start
// 1: finish const http = require ( 'node:http' );
const { AsyncLocalStorage } = require ( 'node:async_hooks' );
const asyncLocalStorage = new AsyncLocalStorage ();
function logWithId ( msg ) {
const id = asyncLocalStorage. getStore ();
console . log ( ` ${id !== undefined ? id : '-' } :` , msg);
}
let idSeq = 0 ;
http. createServer ( ( req, res ) => {
asyncLocalStorage. run (idSeq++, () => {
logWithId ( 'start' );
// Imagine any chain of async operations here
setImmediate ( () => {
logWithId ( 'finish' );
res. end ();
});
});
}). listen ( 8080 );
http. get ( 'http://localhost:8080' );
http. get ( 'http://localhost:8080' );
// Prints:
// 0: start
// 0: finish
// 1: start
// 1: finish copy
Each instance of AsyncLocalStorage maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.
new AsyncLocalStorage() #
History
Version Changes
v19.7.0, v18.16.0
Removed experimental onPropagate option.
v19.2.0, v18.13.0
Add option onPropagate.
v13.10.0, v12.17.0
Added in: v13.10.0, v12.17.0
Creates a new instance of AsyncLocalStorage . Store is only provided within a
run() call or after an enterWith() call.
Static method: AsyncLocalStorage.bind(fn) #
History
Version Changes
v22.15.0
Marking the API stable.
v19.8.0, v18.16.0
Added in: v19.8.0, v18.16.0
* fn <Function> The function to bind to the current execution context.
* Returns: <Function> A new function that calls fn within the captured
execution context.
Binds the given function to the current execution context.
Static method: AsyncLocalStorage.snapshot() #
History
Version Changes
v22.15.0
Marking the API stable.
v19.8.0, v18.16.0
Added in: v19.8.0, v18.16.0
* Returns: <Function> A new function with the signature
(fn: (...args) : R, ...args) : R .
Captures the current execution context and returns a function that accepts a
function as an argument. Whenever the returned function is called, it
calls the function passed to it within the captured context.
const asyncLocalStorage = new AsyncLocalStorage ();
const runInAsyncScope = asyncLocalStorage. run ( 123 , () => AsyncLocalStorage . snapshot ());
const result = asyncLocalStorage. run ( 321 , () => runInAsyncScope ( () => asyncLocalStorage. getStore ()));
console . log (result); // returns 123 copy
AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
async context tracking purposes, for example:
class Foo {
#runInAsyncScope = AsyncLocalStorage . snapshot ();
get ( ) { return this .# runInAsyncScope ( () => asyncLocalStorage. getStore ()); }
}
const foo = asyncLocalStorage. run ( 123 , () => new Foo ());
console . log (asyncLocalStorage. run ( 321 , () => foo. get ())); // returns 123 copy
asyncLocalStorage.disable() #
Added in: v13.10.0, v12.17.0
Stability: 1 - Experimental
Disables the instance of AsyncLocalStorage . All subsequent calls
to asyncLocalStorage.getStore() will return undefined until
asyncLocalStorage.run() or asyncLocalStorage.enterWith() is called again.
When calling asyncLocalStorage.disable() , all current contexts linked to the
instance will be exited.
Calling asyncLocalStorage.disable() is required before the
asyncLocalStorage can be garbage collected. This does not apply to stores
provided by the asyncLocalStorage , as those objects are garbage collected
along with the corresponding async resources.
Use this method when the asyncLocalStorage is not in use anymore
in the current process.
asyncLocalStorage.getStore() #
Added in: v13.10.0, v12.17.0
* Returns: <any>
Returns the current store.
If called outside of an asynchronous context initialized by
calling asyncLocalStorage.run() or asyncLocalStorage.enterWith() , it
returns undefined .
asyncLocalStorage.enterWith(store) #
Added in: v13.11.0, v12.17.0
Stability: 1 - Experimental
* store <any>
Transitions into the context for the remainder of the current
synchronous execution and then persists the store through any following
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
}); copy
This transition will continue for the entire synchronous execution.
This means that if, for example, the context is entered within an event
handler subsequent event handlers will also run within that context unless
specifically bound to another context with an AsyncResource . That is why
run() should be preferred over enterWith() unless there are strong reasons
to use the latter method.
const store = { id : 1 };
emitter. on ( 'my-event' , () => {
asyncLocalStorage. enterWith (store);
});
emitter. on ( 'my-event' , () => {
asyncLocalStorage. getStore (); // Returns the same object
});
asyncLocalStorage. getStore (); // Returns undefined
emitter. emit ( 'my-event' );
asyncLocalStorage. getStore (); // Returns the same object copy
asyncLocalStorage.run(store, callback[, ...args]) #
Added in: v13.10.0, v12.17.0
* store <any>
* callback <Function>
* ...args <any>
Runs a function synchronously within a context and returns its
return value. The store is not accessible outside of the callback function.
The store is accessible to any asynchronous operations created within the
callback.
The optional args are passed to the callback function.
If the callback function throws an error, the error is thrown by run() too.
The stacktrace is not impacted by this call and the context is exited.
Example:
const store = { id : 2 };
try {
asyncLocalStorage. run (store, () => {
asyncLocalStorage. getStore (); // Returns the store object
setTimeout ( () => {
asyncLocalStorage. getStore (); // Returns the store object
}, 200 );
throw new Error ();
});
} catch (e) {
asyncLocalStorage. getStore (); // Returns undefined
// The error will be caught here
} copy
asyncLocalStorage.exit(callback[, ...args]) #
Added in: v13.10.0, v12.17.0
Stability: 1 - Experimental
* callback <Function>
* ...args <any>
Runs a function synchronously outside of a context and returns its
return value. The store is not accessible within the callback function or
the asynchronous operations created within the callback. Any getStore()
call done within the callback function will always return undefined .
The optional args are passed to the callback function.
If the callback function throws an error, the error is thrown by exit() too.
The stacktrace is not impacted by this call and the context is re-entered.
Example:
// Within a call to run
try {
asyncLocalStorage. getStore (); // Returns the store object or value
asyncLocalStorage. exit ( () => {
asyncLocalStorage. getStore (); // Returns undefined
throw new Error ();
});
} catch (e) {
asyncLocalStorage. getStore (); // Returns the same object or value
// The error will be caught here
} copy
Usage with async/await #
If, within an async function, only one await call is to run within a context,
the following pattern should be used:
async function fn ( ) {
await asyncLocalStorage. run ( new Map (), () => {
asyncLocalStorage. getStore (). set ( 'key' , value);
return foo (); // The return value of foo will be awaited
});
} copy
In this example, the store is only available in the callback function and the
functions called by foo . Outside of run , calling getStore will return
undefined .
Troubleshooting: Context loss #
In most cases, AsyncLocalStorage works without issues. In rare situations, the
current store is lost in one of the asynchronous operations.
If your code is callback-based, it is enough to promisify it with
util.promisify() so it starts working with native promises.
If you need to use a callback-based API or your code assumes
a custom thenable implementation, use the AsyncResource class
to associate the asynchronous operation with the correct execution context.
Find the function call responsible for the context loss by logging the content
of asyncLocalStorage.getStore() after the calls you suspect are responsible
for the loss. When the code logs undefined , the last callback called is
probably responsible for the context loss.
Class: AsyncResource #
History
Version Changes
v16.4.0
AsyncResource is now Stable. Previously, it had been Experimental.
The class AsyncResource is designed to be extended by the embedder's async
resources. Using this, users can easily trigger the lifetime events of their
own resources.
The init hook will trigger when an AsyncResource is instantiated.
The following is an overview of the AsyncResource API.
import { AsyncResource , executionAsyncId } from 'node:async_hooks' ;
// AsyncResource() is meant to be extended. Instantiating a
// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
// async_hook.executionAsyncId() is used.
const asyncResource = new AsyncResource (
type, { triggerAsyncId : executionAsyncId (), requireManualDestroy : false },
);
// Run a function in the execution context of the resource. This will
// * establish the context of the resource
// * trigger the AsyncHooks before callbacks
// * call the provided function `fn` with the supplied arguments
// * trigger the AsyncHooks after callbacks
// * restore the original execution context
asyncResource. runInAsyncScope (fn, thisArg, ...args);
// Call AsyncHooks destroy callbacks.
asyncResource. emitDestroy ();
// Return the unique ID assigned to the AsyncResource instance.
asyncResource. asyncId ();
// Return the trigger ID for the AsyncResource instance.
asyncResource. triggerAsyncId (); const { AsyncResource , executionAsyncId } = require ( 'node:async_hooks' );
// AsyncResource() is meant to be extended. Instantiating a
// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
// async_hook.executionAsyncId() is used.
const asyncResource = new AsyncResource (
type, { triggerAsyncId : executionAsyncId (), requireManualDestroy : false },
);
// Run a function in the execution context of the resource. This will
// * establish the context of the resource
// * trigger the AsyncHooks before callbacks
// * call the provided function `fn` with the supplied arguments
// * trigger the AsyncHooks after callbacks
// * restore the original execution context
asyncResource. runInAsyncScope (fn, thisArg, ...args);
// Call AsyncHooks destroy callbacks.
asyncResource. emitDestroy ();
// Return the unique ID assigned to the AsyncResource instance.
asyncResource. asyncId ();
// Return the trigger ID for the AsyncResource instance.
asyncResource. triggerAsyncId (); copy
new AsyncResource(type[, options]) #
* type <string> The type of async event.
* options <Object>
* triggerAsyncId <number> The ID of the execution context that created this
async event. Default: executionAsyncId() .
* requireManualDestroy <boolean> If set to true , disables emitDestroy
when the object is garbage collected. This usually does not need to be set
(even if emitDestroy is called manually), unless the resource's asyncId
is retrieved and the sensitive API's emitDestroy is called with it.
When set to false , the emitDestroy call on garbage collection
will only take place if there is at least one active destroy hook.
Default: false .
Example usage:
class DBQuery extends AsyncResource {
constructor ( db ) {
super ( 'DBQuery' );
this . db = db;
}
getInfo ( query, callback ) {
this . db . get (query, ( err, data ) => {
this . runInAsyncScope (callback, null , err, data);
});
}
close ( ) {
this . db = null ;
this . emitDestroy ();
}
} copy
Static method: AsyncResource.bind(fn[, type[, thisArg]]) #
History
Version Changes
v20.0.0
The asyncResource property added to the bound function has been deprecated and will be removed in a future version.
v17.8.0, v16.15.0
Changed the default when thisArg is undefin
Links found on this page
- Skip to content [direct]
- Node.js [direct]
- About this documentation [direct]
- Usage and example [direct]
- Assertion testing [direct]
- Async hooks [direct]
- Buffer [direct]
- C++ addons [direct]
- C/C++ addons with Node-API [direct]
- C++ embedder API [direct]
- Child processes [direct]
- Cluster [direct]
- Command-line options [direct]
- Console [direct]
- Crypto [direct]
- Debugger [direct]
- Deprecated APIs [direct]
- Diagnostics Channel [direct]
- DNS [direct]
- Domain [direct]
- Environment Variables [direct]
- Errors [direct]
- Events [direct]
- File system [direct]
- Globals [direct]
- HTTP [direct]
- HTTP/2 [direct]
- HTTPS [direct]
- Inspector [direct]
- Internationalization [direct]
- Modules: CommonJS modules [direct]
- Modules: ECMAScript modules [direct]
- Modules: node:module API [direct]
- Modules: Packages [direct]
- Modules: TypeScript [direct]
- Net [direct]
- OS [direct]
- Path [direct]
- Performance hooks [direct]
- Permissions [direct]
- Process [direct]
- Punycode [direct]
- Query strings [direct]
- Readline [direct]
- REPL [direct]
- Report [direct]
- Single executable applications [direct]
- SQLite [direct]
- Stream [direct]
- String decoder [direct]
- Test runner [direct]
- Timers [direct]
- TLS/SSL [direct]
- Trace events [direct]
- TTY [direct]
- UDP/datagram [direct]
- URL [direct]
- Utilities [direct]
- V8 [direct]
- VM [direct]
- WASI [direct]
- Web Crypto API [direct]
- Web Streams API [direct]
- Worker threads [direct]
- Zlib [direct]
- Code repository and issue tracker [direct]
- Index [direct]
- 26.x [direct]
- 25.x [direct]
- 24.x LTS [direct]
- 23.x [direct]
- 21.x [direct]
- 20.x [direct]
- 19.x [direct]
- 18.x [direct]
- 17.x [direct]
- 16.x [direct]
- View on single page [direct]
- View as JSON [direct]
- Edit on GitHub [direct]