Skip to main content
Skip to main content

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.

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();

Methods

asyncId

Returns

numbernumber
The unique asyncId assigned to the resource.

bind

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

Parameters

fnFuncRequired
The function to bind to the current AsyncResource.

Returns

Since

v14.8.0, v12.19.0


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.

Returns

AsyncResourceAsyncResourceRequired
A reference to asyncResource.

runInAsyncScope

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.

Parameters

fn(this: This, ...args: any[]) => ResultRequired
The function to call in the execution context of this async resource.
thisArgThis
The receiver to be used for the function call.
argsany[]Required
Optional arguments to pass to the function.

Returns

Since

v9.6.0


triggerAsyncId

Returns

numbernumber
The same triggerAsyncId that is passed to the AsyncResource constructor.

bind

Binds the given function to the current execution context.

Parameters

fnFuncRequired
The function to bind to the current execution context.
typestring
An optional name to associate with the underlying AsyncResource.
thisArgThisArg

Returns

Since

v14.8.0, v12.19.0

Was this section helpful?