温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com/reference/node/async_hooks
点击访问原文链接

Node.js async_hooks module | API Reference | Bun

Node.js async_hooks module | API Reference | BunBuildDocsReferenceGuidesBlogDiscord/node:async_hooksCAsyncLocalStorageCAsyncResourceNasyncWrapProvidersFcreateHookFexecutionAsyncIdFexecutionAsyncResourceFtriggerAsyncId

Search the reference...

/

BuildDocsReferenceGuidesBlogDiscord/node:async_hooksCAsyncLocalStorageCAsyncResourceNasyncWrapProvidersFcreateHookFexecutionAsyncIdFexecutionAsyncResourceFtriggerAsyncId

Node.js module

async_hooksThe 'node:async_hooks' module provides hooks to track the lifecycle of asynchronous resources in Node.js—init, before, after, and destroy—for tasks like promises, timers, callbacks, and I/O operations.

It's useful for keeping state across async callbacks, measuring performance, or building custom logging and tracing tools in your application.

Works in Bun

AsyncLocalStorage and AsyncResource are implemented. However, v8 promise hooks required for broader compatibility are not called.

namespace asyncWrapProvidersconst CHECKPRIMEREQUEST: numberconst CIPHERREQUEST: numberconst DERIVEBITSREQUEST: numberconst DIRHANDLE: numberconst DNSCHANNEL: numberconst ELDHISTOGRAM: numberconst FILEHANDLE: numberconst FILEHANDLECLOSEREQ: numberconst FIXEDSIZEBLOBCOPY: numberconst FSEVENTWRAP: numberconst FSREQCALLBACK: numberconst FSREQPROMISE: numberconst GETADDRINFOREQWRAP: numberconst GETNAMEINFOREQWRAP: numberconst HASHREQUEST: numberconst HEAPSNAPSHOT: numberconst HTTP2PING: numberconst HTTP2SESSION: numberconst HTTP2SETTINGS: numberconst HTTP2STREAM: numberconst HTTPCLIENTREQUEST: numberconst HTTPINCOMINGMESSAGE: numberconst JSSTREAM: numberconst JSUDPWRAP: numberconst KEYEXPORTREQUEST: numberconst KEYGENREQUEST: numberconst KEYPAIRGENREQUEST: numberconst MESSAGEPORT: numberconst NONE: numberconst PBKDF2REQUEST: numberconst PIPECONNECTWRAP: numberconst PIPESERVERWRAP: numberconst PIPEWRAP: numberconst PROCESSWRAP: numberconst PROMISE: numberconst QUERYWRAP: numberconst RANDOMBYTESREQUEST: numberconst RANDOMPRIMEREQUEST: numberconst SCRYPTREQUEST: numberconst SHUTDOWNWRAP: numberconst SIGINTWATCHDOG: numberconst SIGNALWRAP: numberconst SIGNREQUEST: numberconst STATWATCHER: numberconst STREAMPIPE: numberconst TCPCONNECTWRAP: numberconst TCPSERVERWRAP: numberconst TCPWRAP: numberconst TLSWRAP: numberconst TTYWRAP: numberconst UDPSENDWRAP: numberconst UDPWRAP: numberconst VERIFYREQUEST: numberconst WORKER: numberconst WORKERHEAPSNAPSHOT: numberconst WRITEWRAP: numberconst ZLIB: number { 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 ``` Each instance of `AsyncLocalStorage` maintains an independent storage context. Multiple instances can safely exist simultaneously without risk of interfering with each other's data." data-algolia-static="false" data-algolia-merged="false" data-type="Class">class AsyncLocalStorageT>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 Each instance of AsyncLocalStorage maintains an independent storage context. Multiple instances can safely exist simultaneously without risk of interfering with each other's data.

readonly name: stringThe name of the AsyncLocalStorage instance if provided.

disable(): void;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(); // Returns the same object }); ``` 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 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 ```" data-algolia-static="false" data-algolia-merged="false" data-type="Method">enterWith(store: T): void;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 }); 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 { asyncLocalStorage.getStore(); // Returns undefined throw new Error(); }); } catch (e) { asyncLocalStorage.getStore(); // Returns the same object or value // The error will be caught here } ```" data-algolia-static="false" data-algolia-merged="false" data-type="Method">exitR, TArgs extends any[]>(callback: (...args: TArgs) => R,...args: TArgs): R;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 } getStore(): undefined | T;Returns the current store. If called outside of an asynchronous context initialized by calling asyncLocalStorage.run() or asyncLocalStorage.enterWith(), it returns undefined.

{ 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 } ```" data-algolia-static="false" data-algolia-merged="false" data-type="Method">runR>(store: T,callback: () => R): R;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 } runR, TArgs extends any[]>(store: T,callback: (...args: TArgs) => R,...args: TArgs): R;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 } static bindFunc extends (...args: any[]) => any>(fn: Func): Func;Binds the given function to the current execution context.

@param fnThe function to bind to the current execution context.

@returnsA new function that calls fn within the captured execution context.

AsyncLocalStorage.snapshot()); const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); console.log(result); // returns 123 ``` AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple async context tracking purposes, for example: ```js 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 ```" data-algolia-static="true" data-algolia-merged="false" data-type="Method">static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => 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 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 @returnsA new function with the signature (fn: (...args) : R, ...args) : R.

class AsyncResourceThe 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(); asyncId(): number;@returnsThe unique asyncId assigned to the resource.

bindFunc extends (...args: any[]) => any>(fn: Func): Func;Binds the given function to execute to this AsyncResource's scope.

@param fnThe function to bind to the current AsyncResource.

emitDestroy(): this;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.

@returnsA reference to asyncResource.

runInAsyncScopeThis, Result>(fn: (this: This, ...args: any[]) => Result,thisArg?: This,...args: any[]): Result;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.

@param fnThe function to call in the execution context of this async resource.

@param thisArgThe receiver to be used for the function call.

@param argsOptional arguments to pass to the function.

triggerAsyncId(): number;@returnsThe same triggerAsyncId that is passed to the AsyncResource constructor.

static bindFunc extends (this: ThisArg, ...args: any[]) => any, ThisArg>(fn: Func,type?: string,thisArg?: ThisArg): Func;Binds the given function to the current execution context.

@param fnThe function to bind to the current execution context.

@param typeAn optional name to associate with the underlying AsyncResource.

function createHook(callbacks: HookCallbacks): AsyncHook;Registers functions to be called for different lifetime events of each async operation.

The callbacks init()/before()/after()/destroy() are called for the respective asynchronous event during a resource's lifetime.

All callbacks are optional. For example, if only resource cleanup needs to be tracked, then only the destroy callback needs to be passed. The specifics of all functions that can be passed to callbacks is in the Hook Callbacks section.

import { createHook } from 'node:async_hooks'; const asyncHook = createHook({ init(asyncId, type, triggerAsyncId, resource) { }, destroy(asyncId) { }, }); The callbacks will be inherited via the prototype chain:

class MyAsyncCallbacks { init(asyncId, type, triggerAsyncId, resource) { } destroy(asyncId) {} } class MyAddedCallbacks extends MyAsyncCallbacks { before(asyncId) { } after(asyncId) { } } const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); Because promises are asynchronous resources whose lifecycle is tracked via the async hooks mechanism, the init(), before(), after(), anddestroy() callbacks must not be async functions that return promises.

@param callbacksThe Hook Callbacks to register

@returnsInstance used for disabling and enabling hooks

{ console.log(executionAsyncId()); // 6 - open() }); ``` The ID returned from `executionAsyncId()` is related to execution timing, not causality (which is covered by `triggerAsyncId()`): ```js const server = net.createServer((conn) => { // Returns the ID of the server, not of the new connection, because the // callback runs in the execution scope of the server's MakeCallback(). async_hooks.executionAsyncId(); }).listen(port, () => { // Returns the ID of a TickObject (process.nextTick()) because all // callbacks passed to .listen() are wrapped in a nextTick(). async_hooks.executionAsyncId(); }); ``` Promise contexts may not get precise `executionAsyncIds` by default. See the section on [promise execution tracking](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#promise-execution-tracking)." data-algolia-static="false" data-algolia-merged="false" data-type="Function">function executionAsyncId(): number;import { executionAsyncId } from 'node:async_hooks'; import fs from 'node:fs'; console.log(executionAsyncId()); // 1 - bootstrap const path = '.'; fs.open(path, 'r', (err, fd) => { console.log(executionAsyncId()); // 6 - open() }); The ID returned from executionAsyncId() is related to execution timing, not causality (which is covered by triggerAsyncId()):

const server = net.createServer((conn) => { // Returns the ID of the server, not of the new connection, because the // callback runs in the execution scope of the server's MakeCallback(). async_hooks.executionAsyncId(); }).listen(port, () => { // Returns the ID of a TickObject (process.nextTick()) because all // callbacks passed to .listen() are wrapped in a nextTick(). async_hooks.executionAsyncId(); }); Promise contexts may not get precise executionAsyncIds by default. See the section on promise execution tracking.

@returnsThe asyncId of the current execution context. Useful to track when something calls.

{ console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap }); ``` This can be used to implement continuation local storage without the use of a tracking `Map` to store the metadata: ```js import { createServer } from 'node:http'; import { executionAsyncId, executionAsyncResource, createHook, } from 'node:async_hooks'; const sym = Symbol('state'); // Private symbol to avoid pollution createHook({ init(asyncId, type, triggerAsyncId, resource) { const cr = executionAsyncResource(); if (cr) { resource[sym] = cr[sym]; } }, }).enable(); const server = createServer((req, res) => { executionAsyncResource()[sym] = { state: req.url }; setTimeout(function() { res.end(JSON.stringify(executionAsyncResource()[sym])); }, 100); }).listen(3000); ```" data-algolia-static="false" data-algolia-merged="false" data-type="Function">function executionAsyncResource(): object;Resource objects returned by executionAsyncResource() are most often internal Node.js handle objects with undocumented APIs. Using any functions or properties on the object is likely to crash your application and should be avoided.

Using executionAsyncResource() in the top-level execution context will return an empty object as there is no handle or request object to use, but having an object representing the top-level can be helpful.

import { open } from 'node:fs'; import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; console.log(executionAsyncId(), executionAsyncResource()); // 1 {} open(new URL(import.meta.url), 'r', (err, fd) => { console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap }); This can be used to implement continuation local storage without the use of a tracking Map to store the metadata:

import { createServer } from 'node:http'; import { executionAsyncId, executionAsyncResource, createHook, } from 'node:async_hooks'; const sym = Symbol('state'); // Private symbol to avoid pollution createHook({ init(asyncId, type, triggerAsyncId, resource) { const cr = executionAsyncResource(); if (cr) { resource[sym] = cr[sym]; } }, }).enable(); const server = createServer((req, res) => { executionAsyncResource()[sym] = { state: req.url }; setTimeout(function() { res.end(JSON.stringify(executionAsyncResource()[sym])); }, 100); }).listen(3000); @returnsThe resource representing the current execution. Useful to store data within the resource.

{ // The resource that caused (or triggered) this callback to be called // was that of the new connection. Thus the return value of triggerAsyncId() // is the asyncId of "conn". async_hooks.triggerAsyncId(); }).listen(port, () => { // Even though all callbacks passed to .listen() are wrapped in a nextTick() // the callback itself exists because the call to the server's .listen() // was made. So the return value would be the ID of the server. async_hooks.triggerAsyncId(); }); ``` Promise contexts may not get valid `triggerAsyncId`s by default. See the section on [promise execution tracking](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#promise-execution-tracking)." data-algolia-static="false" data-algolia-merged="false" data-type="Function">function triggerAsyncId(): number;const server = net.createServer((conn) => { // The resource that caused (or triggered) this callback to be called // was that of the new connection. Thus the return value of triggerAsyncId() // is the asyncId of "conn". async_hooks.triggerAsyncId(); }).listen(port, () => { // Even though all callbacks passed to .listen() are wrapped in a nextTick() // the callback itself exists because the call to the server's .listen() // was made. So the return value would be the ID of the server. async_hooks.triggerAsyncId(); }); Promise contexts may not get valid triggerAsyncIds by default. See the section on promise execution tracking.

@returnsThe ID of the resource responsible for calling the callback that is currently being executed.

Type definitionsinterface AsyncHookdisable(): this;Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.

enable(): this;Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop.

interface AsyncLocalStorageOptionsdefaultValue?: anyThe default value to be used when no store is provided.

name?: stringA name for the AsyncLocalStorage value.

interface AsyncResourceOptionsrequireManualDestroy?: booleanDisables automatic 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.

triggerAsyncId?: numberThe ID of the execution context that created this async event.

interface HookCallbacksafter(asyncId: number): void;Called immediately after the callback specified in before is completed.

If an uncaught exception occurs during execution of the callback, then after will run after the 'uncaughtException' event is emitted or a domain's handler runs.

@param asyncIdthe unique identifier assigned to the resource which has executed the callback.

before(asyncId: number): void;When an asynchronous operation is initiated or completes a callback is called to notify the user. The before callback is called just before said callback is executed.

@param asyncIdthe unique identifier assigned to the resource about to execute the callback.

destroy(asyncId: number): void;Called after the resource corresponding to asyncId is destroyed

@param asyncIda unique ID for the async resource

init(asyncId: number,type: string,triggerAsyncId: number,resource: object): void;Called when a class is constructed that has the possibility to emit an asynchronous event.

@param asyncIdA unique ID for the async resource

@param typeThe type of the async resource

@param triggerAsyncIdThe unique ID of the async resource in whose execution context this async resource was created

@param resourceReference to the resource representing the async operation, needs to be released during destroy

promiseResolve(asyncId: number): void;Called when a promise has resolve() called. This may not be in the same execution id as the promise itself.

@param asyncIdthe unique id for the promise that was resolve()d.

Resources

ReferenceDocsGuidesDiscordMerch StoreGitHubBlog 

Toolkit

RuntimePackage managerTest runnerBundlerPackage runner

Project

Bun 1.0Bun 1.1Bun 1.2Bun 1.3RoadmapContributingLicenseBaked with ❤️ in San Francisco

We're hiring →

智能索引记录