home / documentation / v19 / async_context

Asynchronous context tracking

目录

Added in: v16.4.0

稳定性: 2 - Stable

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:

MJS
CJS

C AsyncLocalStorage

历史
版本更改
v16.4.0AsyncLocalStorage is now Stable. Previously, it had been Experimental.
v13.10.0, v12.17.0Added 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.

MJS
CJS

Each instance of AsyncLocalStorage maintains an independent storage context. Multiple instances can safely exist simultaneously without risk of interfering with each other's data.

M new AsyncLocalStorage()

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.

M asyncLocalStorage.disable()

Added in: v13.10.0, v12.17.0

稳定性: 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.

M asyncLocalStorage.getStore()

Added in: v13.10.0, v12.17.0

Returns the current store. If called outside of an asynchronous context initialized by calling asyncLocalStorage.run() or asyncLocalStorage.enterWith(), it returns undefined.

M asyncLocalStorage.enterWith(store)

Added in: v13.11.0, v12.17.0

稳定性: 1 - Experimental

Transitions into the context for the remainder of the current synchronous execution and then persists the store through any following asynchronous calls.

Example:

JS

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.

JS

M asyncLocalStorage.run(store, callback[, ...args])

Added in: v13.10.0, v12.17.0

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:

JS

M asyncLocalStorage.exit(callback[, ...args])

Added in: v13.10.0, v12.17.0

稳定性: 1 - Experimental

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:

JS

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:

JS

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.

C AsyncResource

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.

MJS
CJS

M 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:

JS

Static method: AsyncResource.bind(fn[, type[, thisArg]])

历史
版本更改
v17.8.0, v16.15.0Changed the default when `thisArg` is undefined to use `this` from the caller.
v16.0.0Added optional thisArg.
v14.8.0, v12.19.0Added in: v14.8.0, v12.19.0
  • fn Function The function to bind to the current execution context.
  • type string An optional name to associate with the underlying AsyncResource.
  • thisArg any

Binds the given function to the current execution context.

The returned function will have an asyncResource property referencing the AsyncResource to which the function is bound.

M asyncResource.bind(fn[, thisArg])

历史
版本更改
v17.8.0, v16.15.0Changed the default when `thisArg` is undefined to use `this` from the caller.
v16.0.0Added optional thisArg.
v14.8.0, v12.19.0Added in: v14.8.0, v12.19.0
  • fn Function The function to bind to the current AsyncResource.
  • thisArg any

Binds the given function to execute to this AsyncResource's scope.

The returned function will have an asyncResource property referencing the AsyncResource to which the function is bound.

M asyncResource.runInAsyncScope(fn[, thisArg, ...args])

Added in: v9.6.0

  • fn Function The function to call in the execution context of this async resource.
  • thisArg any The receiver to be used for the function call.
  • ...args any Optional arguments to pass to the function.

Call the provided function with the provided arguments in the execution context of the async resource. This will establish the context, trigger the AsyncHooks before callbacks, call the function, trigger the AsyncHooks after callbacks, and then restore the original execution context.

M asyncResource.emitDestroy()

Call all destroy hooks. This should only ever be called once. An error will be thrown if it is called more than once. This must be manually called. If the resource is left to be collected by the GC then the destroy hooks will never be called.

M asyncResource.asyncId()

  • Returns: number The unique asyncId assigned to the resource.

M asyncResource.triggerAsyncId()

  • Returns: number The same triggerAsyncId that is passed to the AsyncResource constructor.

Using AsyncResource for a Worker thread pool

The following example shows how to use the AsyncResource class to properly provide async tracking for a Worker pool. Other resource pools, such as database connection pools, can follow a similar model.

Assuming that the task is adding two numbers, using a file named task_processor.js with the following content:

MJS
CJS

a Worker pool around it could use the following structure:

MJS
CJS

Without the explicit tracking added by the WorkerPoolTaskInfo objects, it would appear that the callbacks are associated with the individual Worker objects. However, the creation of the Workers is not associated with the creation of the tasks and does not provide information about when tasks were scheduled.

This pool could be used as follows:

MJS
CJS

Integrating AsyncResource with EventEmitter

Event listeners triggered by an EventEmitter may be run in a different execution context than the one that was active when eventEmitter.on() was called.

The following example shows how to use the AsyncResource class to properly associate an event listener with the correct execution context. The same approach can be applied to a Stream or a similar event-driven class.

MJS
CJS