See More

{ "type": "module", "source": "doc/api/async_context.md", "modules": [ { "textRaw": "Asynchronous context tracking", "name": "asynchronous_context_tracking", "introduced_in": "v16.4.0", "type": "module", "stability": 2, "stabilityText": "Stable", "modules": [ { "textRaw": "Introduction", "name": "introduction", "type": "module", "desc": "

These classes are used to associate state and propagate it throughout\ncallbacks and promise chains.\nThey allow storing data throughout the lifetime of a web request\nor any other asynchronous duration. It is similar to thread-local storage\nin other languages.

\n

The AsyncLocalStorage and AsyncResource classes are part of the\nnode:async_hooks module:

\n
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';\n
\n
const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');\n
", "displayName": "Introduction" } ], "classes": [ { "textRaw": "Class: `AsyncLocalStorage`", "name": "AsyncLocalStorage", "type": "class", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [ { "version": "v16.4.0", "pr-url": "https://github.com/nodejs/node/pull/37675", "description": "AsyncLocalStorage is now Stable. Previously, it had been Experimental." } ] }, "desc": "

This class creates stores that stay coherent through asynchronous operations.

\n

While you can create your own implementation on top of the node:async_hooks\nmodule, AsyncLocalStorage should be preferred as it is a performant and memory\nsafe implementation that involves significant optimizations that are non-obvious\nto implement.

\n

The following example uses AsyncLocalStorage to build a simple logger\nthat assigns IDs to incoming HTTP requests and includes them in messages\nlogged within each request.

\n
import http from 'node:http';\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\nfunction logWithId(msg) {\n  const id = asyncLocalStorage.getStore();\n  console.log(`${id !== undefined ? id : '-'}:`, msg);\n}\n\nlet idSeq = 0;\nhttp.createServer((req, res) => {\n  asyncLocalStorage.run(idSeq++, () => {\n    logWithId('start');\n    // Imagine any chain of async operations here\n    setImmediate(() => {\n      logWithId('finish');\n      res.end();\n    });\n  });\n}).listen(8080);\n\nhttp.get('http://localhost:8080');\nhttp.get('http://localhost:8080');\n// Prints:\n//   0: start\n//   0: finish\n//   1: start\n//   1: finish\n
\n
const http = require('node:http');\nconst { AsyncLocalStorage } = require('node:async_hooks');\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\nfunction logWithId(msg) {\n  const id = asyncLocalStorage.getStore();\n  console.log(`${id !== undefined ? id : '-'}:`, msg);\n}\n\nlet idSeq = 0;\nhttp.createServer((req, res) => {\n  asyncLocalStorage.run(idSeq++, () => {\n    logWithId('start');\n    // Imagine any chain of async operations here\n    setImmediate(() => {\n      logWithId('finish');\n      res.end();\n    });\n  });\n}).listen(8080);\n\nhttp.get('http://localhost:8080');\nhttp.get('http://localhost:8080');\n// Prints:\n//   0: start\n//   0: finish\n//   1: start\n//   1: finish\n
\n

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

", "signatures": [ { "textRaw": "`new AsyncLocalStorage([options])`", "name": "AsyncLocalStorage", "type": "ctor", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [ { "version": "v24.0.0", "pr-url": "https://github.com/nodejs/node/pull/57766", "description": "Add `defaultValue` and `name` options." }, { "version": [ "v19.7.0", "v18.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/46386", "description": "Removed experimental onPropagate option." }, { "version": [ "v19.2.0", "v18.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/45386", "description": "Add option onPropagate." } ] }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`defaultValue` {any} The default value to be used when no store is provided.", "name": "defaultValue", "type": "any", "desc": "The default value to be used when no store is provided." }, { "textRaw": "`name` {string} A name for the `AsyncLocalStorage` value.", "name": "name", "type": "string", "desc": "A name for the `AsyncLocalStorage` value." } ], "optional": true } ], "desc": "

Creates a new instance of AsyncLocalStorage. Store is only provided within a\nrun() call or after an enterWith() call.

" } ], "classMethods": [ { "textRaw": "Static method: `AsyncLocalStorage.bind(fn)`", "name": "bind", "type": "classMethod", "meta": { "added": [ "v19.8.0", "v18.16.0" ], "changes": [ { "version": [ "v23.11.0", "v22.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/57510", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function} The function to bind to the current execution context.", "name": "fn", "type": "Function", "desc": "The function to bind to the current execution context." } ], "return": { "textRaw": "Returns: {Function} A new function that calls `fn` within the captured execution context.", "name": "return", "type": "Function", "desc": "A new function that calls `fn` within the captured execution context." } } ], "desc": "

Binds the given function to the current execution context.

" }, { "textRaw": "Static method: `AsyncLocalStorage.snapshot()`", "name": "snapshot", "type": "classMethod", "meta": { "added": [ "v19.8.0", "v18.16.0" ], "changes": [ { "version": [ "v23.11.0", "v22.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/57510", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Function} A new function with the signature `(fn: (...args) : R, ...args) : R`.", "name": "return", "type": "Function", "desc": "A new function with the signature `(fn: (...args) : R, ...args) : R`." } } ], "desc": "

Captures the current execution context and returns a function that accepts a\nfunction as an argument. Whenever the returned function is called, it\ncalls the function passed to it within the captured context.

\n
const asyncLocalStorage = new AsyncLocalStorage();\nconst runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot());\nconst result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));\nconsole.log(result);  // returns 123\n
\n

AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple\nasync context tracking purposes, for example:

\n
class Foo {\n  #runInAsyncScope = AsyncLocalStorage.snapshot();\n\n  get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }\n}\n\nconst foo = asyncLocalStorage.run(123, () => new Foo());\nconsole.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123\n
" } ], "methods": [ { "textRaw": "`asyncLocalStorage.disable()`", "name": "disable", "type": "method", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [] } ], "desc": "

Disables the instance of AsyncLocalStorage. All subsequent calls\nto asyncLocalStorage.getStore() will return undefined until\nasyncLocalStorage.run() or asyncLocalStorage.enterWith() is called again.

\n

When calling asyncLocalStorage.disable(), all current contexts linked to the\ninstance will be exited.

\n

Calling asyncLocalStorage.disable() is required before the\nasyncLocalStorage can be garbage collected. This does not apply to stores\nprovided by the asyncLocalStorage, as those objects are garbage collected\nalong with the corresponding async resources.

\n

Use this method when the asyncLocalStorage is not in use anymore\nin the current process.

" }, { "textRaw": "`asyncLocalStorage.getStore()`", "name": "getStore", "type": "method", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {any}", "name": "return", "type": "any" } } ], "desc": "

Returns the current store.\nIf called outside of an asynchronous context initialized by\ncalling asyncLocalStorage.run() or asyncLocalStorage.enterWith(), it\nreturns undefined.

" }, { "textRaw": "`asyncLocalStorage.enterWith(store)`", "name": "enterWith", "type": "method", "meta": { "added": [ "v13.11.0", "v12.17.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [ { "textRaw": "`store` {any}", "name": "store", "type": "any" } ] } ], "desc": "

Transitions into the context for the remainder of the current\nsynchronous execution and then persists the store through any following\nasynchronous calls.

\n

Example:

\n
const store = { id: 1 };\n// Replaces previous store with the given store object\nasyncLocalStorage.enterWith(store);\nasyncLocalStorage.getStore(); // Returns the store object\nsomeAsyncOperation(() => {\n  asyncLocalStorage.getStore(); // Returns the same object\n});\n
\n

This transition will continue for the entire synchronous execution.\nThis means that if, for example, the context is entered within an event\nhandler subsequent event handlers will also run within that context unless\nspecifically bound to another context with an AsyncResource. That is why\nrun() should be preferred over enterWith() unless there are strong reasons\nto use the latter method.

\n
const store = { id: 1 };\n\nemitter.on('my-event', () => {\n  asyncLocalStorage.enterWith(store);\n});\nemitter.on('my-event', () => {\n  asyncLocalStorage.getStore(); // Returns the same object\n});\n\nasyncLocalStorage.getStore(); // Returns undefined\nemitter.emit('my-event');\nasyncLocalStorage.getStore(); // Returns the same object\n
" }, { "textRaw": "`asyncLocalStorage.run(store, callback[, ...args])`", "name": "run", "type": "method", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`store` {any}", "name": "store", "type": "any" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" }, { "textRaw": "`...args` {any}", "name": "...args", "type": "any", "optional": true } ] } ], "desc": "

Runs a function synchronously within a context and returns its\nreturn value. The store is not accessible outside of the callback function.\nThe store is accessible to any asynchronous operations created within the\ncallback.

\n

The optional args are passed to the callback function.

\n

If the callback function throws an error, the error is thrown by run() too.\nThe stacktrace is not impacted by this call and the context is exited.

\n

Example:

\n
const store = { id: 2 };\ntry {\n  asyncLocalStorage.run(store, () => {\n    asyncLocalStorage.getStore(); // Returns the store object\n    setTimeout(() => {\n      asyncLocalStorage.getStore(); // Returns the store object\n    }, 200);\n    throw new Error();\n  });\n} catch (e) {\n  asyncLocalStorage.getStore(); // Returns undefined\n  // The error will be caught here\n}\n
" }, { "textRaw": "`asyncLocalStorage.exit(callback[, ...args])`", "name": "exit", "type": "method", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" }, { "textRaw": "`...args` {any}", "name": "...args", "type": "any", "optional": true } ] } ], "desc": "

Runs a function synchronously outside of a context and returns its\nreturn value. The store is not accessible within the callback function or\nthe asynchronous operations created within the callback. Any getStore()\ncall done within the callback function will always return undefined.

\n

The optional args are passed to the callback function.

\n

If the callback function throws an error, the error is thrown by exit() too.\nThe stacktrace is not impacted by this call and the context is re-entered.

\n

Example:

\n
// Within a call to run\ntry {\n  asyncLocalStorage.getStore(); // Returns the store object or value\n  asyncLocalStorage.exit(() => {\n    asyncLocalStorage.getStore(); // Returns undefined\n    throw new Error();\n  });\n} catch (e) {\n  asyncLocalStorage.getStore(); // Returns the same object or value\n  // The error will be caught here\n}\n
" }, { "textRaw": "`asyncLocalStorage.withScope(store)`", "name": "withScope", "type": "method", "meta": { "added": [ "v25.9.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [ { "textRaw": "`store` {any}", "name": "store", "type": "any" } ], "return": { "textRaw": "Returns: {RunScope}", "name": "return", "type": "RunScope" } } ], "desc": "

Creates a disposable scope that enters the given store and automatically\nrestores the previous store value when the scope is disposed. This method is\ndesigned to work with JavaScript's explicit resource management (using syntax).

\n

Example:

\n
import { AsyncLocalStorage } from 'node:async_hooks';\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\n{\n  using _ = asyncLocalStorage.withScope('my-store');\n  console.log(asyncLocalStorage.getStore()); // Prints: my-store\n}\n\nconsole.log(asyncLocalStorage.getStore()); // Prints: undefined\n
\n
const { AsyncLocalStorage } = require('node:async_hooks');\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\n{\n  using _ = asyncLocalStorage.withScope('my-store');\n  console.log(asyncLocalStorage.getStore()); // Prints: my-store\n}\n\nconsole.log(asyncLocalStorage.getStore()); // Prints: undefined\n
\n

The withScope() method is particularly useful for managing context in\nsynchronous code where you want to ensure the previous store value is restored\nwhen exiting a block, even if an error is thrown.

\n
import { AsyncLocalStorage } from 'node:async_hooks';\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\ntry {\n  using _ = asyncLocalStorage.withScope('my-store');\n  console.log(asyncLocalStorage.getStore()); // Prints: my-store\n  throw new Error('test');\n} catch (e) {\n  // Store is automatically restored even after error\n  console.log(asyncLocalStorage.getStore()); // Prints: undefined\n}\n
\n
const { AsyncLocalStorage } = require('node:async_hooks');\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\ntry {\n  using _ = asyncLocalStorage.withScope('my-store');\n  console.log(asyncLocalStorage.getStore()); // Prints: my-store\n  throw new Error('test');\n} catch (e) {\n  // Store is automatically restored even after error\n  console.log(asyncLocalStorage.getStore()); // Prints: undefined\n}\n
\n

Important: When using withScope() in async functions before the first\nawait, be aware that the scope change will affect the caller's context. The\nsynchronous portion of an async function (before the first await) runs\nimmediately when called, and when it reaches the first await, it returns the\npromise to the caller. At that point, the scope change becomes visible in the\ncaller's context and will persist in subsequent synchronous code until something\nelse changes the scope value. For async operations, prefer using run() which\nproperly isolates context across async boundaries.

\n
import { AsyncLocalStorage } from 'node:async_hooks';\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\nasync function example() {\n  using _ = asyncLocalStorage.withScope('my-store');\n  console.log(asyncLocalStorage.getStore()); // Prints: my-store\n  await someAsyncOperation(); // Function pauses here and returns promise\n  console.log(asyncLocalStorage.getStore()); // Prints: my-store\n}\n\n// Calling without await\nexample(); // Synchronous portion runs, then pauses at first await\n// After the promise is returned, the scope 'my-store' is now active in caller!\nconsole.log(asyncLocalStorage.getStore()); // Prints: my-store (unexpected!)\n
" } ], "properties": [ { "textRaw": "Type: {string}", "name": "name", "type": "string", "meta": { "added": [ "v24.0.0" ], "changes": [] }, "desc": "

The name of the AsyncLocalStorage instance if provided.

" } ], "modules": [ { "textRaw": "Usage with `async/await`", "name": "usage_with_`async/await`", "type": "module", "desc": "

If, within an async function, only one await call is to run within a context,\nthe following pattern should be used:

\n
async function fn() {\n  await asyncLocalStorage.run(new Map(), () => {\n    asyncLocalStorage.getStore().set('key', value);\n    return foo(); // The return value of foo will be awaited\n  });\n}\n
\n

In this example, the store is only available in the callback function and the\nfunctions called by foo. Outside of run, calling getStore will return\nundefined.

", "displayName": "Usage with `async/await`" }, { "textRaw": "Troubleshooting: Context loss", "name": "troubleshooting:_context_loss", "type": "module", "desc": "

In most cases, AsyncLocalStorage works without issues. In rare situations, the\ncurrent store is lost in one of the asynchronous operations.

\n

If your code is callback-based, it is enough to promisify it with\nutil.promisify() so it starts working with native promises.

\n

If you need to use a callback-based API or your code assumes\na custom thenable implementation, use the AsyncResource class\nto associate the asynchronous operation with the correct execution context.\nFind the function call responsible for the context loss by logging the content\nof asyncLocalStorage.getStore() after the calls you suspect are responsible\nfor the loss. When the code logs undefined, the last callback called is\nprobably responsible for the context loss.

", "displayName": "Troubleshooting: Context loss" } ] }, { "textRaw": "Class: `RunScope`", "name": "RunScope", "type": "class", "meta": { "added": [ "v25.9.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

A disposable scope returned by asyncLocalStorage.withScope() that\nautomatically restores the previous store value when disposed. This class\nimplements the Explicit Resource Management protocol and is designed to work\nwith JavaScript's using syntax.

\n

The scope automatically restores the previous store value when the using block\nexits, whether through normal completion or by throwing an error.

", "methods": [ { "textRaw": "`scope.dispose()`", "name": "dispose", "type": "method", "meta": { "added": [ "v25.9.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Explicitly ends the scope and restores the previous store value. This method\nis idempotent: calling it multiple times has the same effect as calling it once.

\n

The [Symbol.dispose]() method defers to dispose().

\n

If withScope() is called without the using keyword, dispose() must be\ncalled manually to restore the previous store value. Forgetting to call\ndispose() will cause the store value to persist for the remainder of the\ncurrent execution context:

\n
import { AsyncLocalStorage } from 'node:async_hooks';\n\nconst storage = new AsyncLocalStorage();\n\n// Without using, the scope must be disposed manually\nconst scope = storage.withScope('my-store');\n// storage.getStore() === 'my-store' here\n\nscope.dispose(); // Restore previous value\n// storage.getStore() === undefined here\n
\n
const { AsyncLocalStorage } = require('node:async_hooks');\n\nconst storage = new AsyncLocalStorage();\n\n// Without using, the scope must be disposed manually\nconst scope = storage.withScope('my-store');\n// storage.getStore() === 'my-store' here\n\nscope.dispose(); // Restore previous value\n// storage.getStore() === undefined here\n
" } ] }, { "textRaw": "Class: `AsyncResource`", "name": "AsyncResource", "type": "class", "meta": { "changes": [ { "version": "v16.4.0", "pr-url": "https://github.com/nodejs/node/pull/37675", "description": "AsyncResource is now Stable. Previously, it had been Experimental." } ] }, "desc": "

The class AsyncResource is designed to be extended by the embedder's async\nresources. Using this, users can easily trigger the lifetime events of their\nown resources.

\n

The init hook will trigger when an AsyncResource is instantiated.

\n

The following is an overview of the AsyncResource API.

\n
import { AsyncResource, executionAsyncId } from 'node:async_hooks';\n\n// AsyncResource() is meant to be extended. Instantiating a\n// new AsyncResource() also triggers init. If triggerAsyncId is omitted then\n// async_hook.executionAsyncId() is used.\nconst asyncResource = new AsyncResource(\n  type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },\n);\n\n// Run a function in the execution context of the resource. This will\n// * establish the context of the resource\n// * trigger the AsyncHooks before callbacks\n// * call the provided function `fn` with the supplied arguments\n// * trigger the AsyncHooks after callbacks\n// * restore the original execution context\nasyncResource.runInAsyncScope(fn, thisArg, ...args);\n\n// Call AsyncHooks destroy callbacks.\nasyncResource.emitDestroy();\n\n// Return the unique ID assigned to the AsyncResource instance.\nasyncResource.asyncId();\n\n// Return the trigger ID for the AsyncResource instance.\nasyncResource.triggerAsyncId();\n
\n
const { AsyncResource, executionAsyncId } = require('node:async_hooks');\n\n// AsyncResource() is meant to be extended. Instantiating a\n// new AsyncResource() also triggers init. If triggerAsyncId is omitted then\n// async_hook.executionAsyncId() is used.\nconst asyncResource = new AsyncResource(\n  type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },\n);\n\n// Run a function in the execution context of the resource. This will\n// * establish the context of the resource\n// * trigger the AsyncHooks before callbacks\n// * call the provided function `fn` with the supplied arguments\n// * trigger the AsyncHooks after callbacks\n// * restore the original execution context\nasyncResource.runInAsyncScope(fn, thisArg, ...args);\n\n// Call AsyncHooks destroy callbacks.\nasyncResource.emitDestroy();\n\n// Return the unique ID assigned to the AsyncResource instance.\nasyncResource.asyncId();\n\n// Return the trigger ID for the AsyncResource instance.\nasyncResource.triggerAsyncId();\n
", "signatures": [ { "textRaw": "`new AsyncResource(type[, options])`", "name": "AsyncResource", "type": "ctor", "params": [ { "textRaw": "`type` {string} The type of async event.", "name": "type", "type": "string", "desc": "The type of async event." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`triggerAsyncId` {number} The ID of the execution context that created this async event. **Default:** `executionAsyncId()`.", "name": "triggerAsyncId", "type": "number", "default": "`executionAsyncId()`", "desc": "The ID of the execution context that created this async event." }, { "textRaw": "`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`.", "name": "requireManualDestroy", "type": "boolean", "default": "`false`", "desc": "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." } ], "optional": true } ], "desc": "

Example usage:

\n
class DBQuery extends AsyncResource {\n  constructor(db) {\n    super('DBQuery');\n    this.db = db;\n  }\n\n  getInfo(query, callback) {\n    this.db.get(query, (err, data) => {\n      this.runInAsyncScope(callback, null, err, data);\n    });\n  }\n\n  close() {\n    this.db = null;\n    this.emitDestroy();\n  }\n}\n
" } ], "classMethods": [ { "textRaw": "Static method: `AsyncResource.bind(fn[, type[, thisArg]])`", "name": "bind", "type": "classMethod", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [ { "version": "v20.0.0", "pr-url": "https://github.com/nodejs/node/pull/46432", "description": "The `asyncResource` property added to the bound function has been deprecated and will be removed in a future version." }, { "version": [ "v17.8.0", "v16.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/42177", "description": "Changed the default when `thisArg` is undefined to use `this` from the caller." }, { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/36782", "description": "Added optional thisArg." } ] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function} The function to bind to the current execution context.", "name": "fn", "type": "Function", "desc": "The function to bind to the current execution context." }, { "textRaw": "`type` {string} An optional name to associate with the underlying `AsyncResource`.", "name": "type", "type": "string", "desc": "An optional name to associate with the underlying `AsyncResource`.", "optional": true }, { "textRaw": "`thisArg` {any}", "name": "thisArg", "type": "any", "optional": true } ] } ], "desc": "

Binds the given function to the current execution context.

" } ], "methods": [ { "textRaw": "`asyncResource.bind(fn[, thisArg])`", "name": "bind", "type": "method", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [ { "version": "v20.0.0", "pr-url": "https://github.com/nodejs/node/pull/46432", "description": "The `asyncResource` property added to the bound function has been deprecated and will be removed in a future version." }, { "version": [ "v17.8.0", "v16.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/42177", "description": "Changed the default when `thisArg` is undefined to use `this` from the caller." }, { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/36782", "description": "Added optional thisArg." } ] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function} The function to bind to the current `AsyncResource`.", "name": "fn", "type": "Function", "desc": "The function to bind to the current `AsyncResource`." }, { "textRaw": "`thisArg` {any}", "name": "thisArg", "type": "any", "optional": true } ] } ], "desc": "

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

" }, { "textRaw": "`asyncResource.runInAsyncScope(fn[, thisArg, ...args])`", "name": "runInAsyncScope", "type": "method", "meta": { "added": [ "v9.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function} The function to call in the execution context of this async resource.", "name": "fn", "type": "Function", "desc": "The function to call in the execution context of this async resource." }, { "textRaw": "`thisArg` {any} The receiver to be used for the function call.", "name": "thisArg", "type": "any", "desc": "The receiver to be used for the function call.", "optional": true }, { "textRaw": "`...args` {any} Optional arguments to pass to the function.", "name": "...args", "type": "any", "desc": "Optional arguments to pass to the function.", "optional": true } ] } ], "desc": "

Call the provided function with the provided arguments in the execution context\nof the async resource. This will establish the context, trigger the AsyncHooks\nbefore callbacks, call the function, trigger the AsyncHooks after callbacks, and\nthen restore the original execution context.

" }, { "textRaw": "`asyncResource.emitDestroy()`", "name": "emitDestroy", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {AsyncResource} A reference to `asyncResource`.", "name": "return", "type": "AsyncResource", "desc": "A reference to `asyncResource`." } } ], "desc": "

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

" }, { "textRaw": "`asyncResource.asyncId()`", "name": "asyncId", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {number} The unique `asyncId` assigned to the resource.", "name": "return", "type": "number", "desc": "The unique `asyncId` assigned to the resource." } } ] }, { "textRaw": "`asyncResource.triggerAsyncId()`", "name": "triggerAsyncId", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {number} The same `triggerAsyncId` that is passed to the `AsyncResource` constructor.", "name": "return", "type": "number", "desc": "The same `triggerAsyncId` that is passed to the `AsyncResource` constructor." } } ], "desc": "

" } ], "modules": [ { "textRaw": "Using `AsyncResource` for a `Worker` thread pool", "name": "using_`asyncresource`_for_a_`worker`_thread_pool", "type": "module", "desc": "

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

\n

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

\n
import { parentPort } from 'node:worker_threads';\nparentPort.on('message', (task) => {\n  parentPort.postMessage(task.a + task.b);\n});\n
\n
const { parentPort } = require('node:worker_threads');\nparentPort.on('message', (task) => {\n  parentPort.postMessage(task.a + task.b);\n});\n
\n

a Worker pool around it could use the following structure:

\n
import { AsyncResource } from 'node:async_hooks';\nimport { EventEmitter } from 'node:events';\nimport { Worker } from 'node:worker_threads';\n\nconst kTaskInfo = Symbol('kTaskInfo');\nconst kWorkerFreedEvent = Symbol('kWorkerFreedEvent');\n\nclass WorkerPoolTaskInfo extends AsyncResource {\n  constructor(callback) {\n    super('WorkerPoolTaskInfo');\n    this.callback = callback;\n  }\n\n  done(err, result) {\n    this.runInAsyncScope(this.callback, null, err, result);\n    this.emitDestroy();  // `TaskInfo`s are used only once.\n  }\n}\n\nexport default class WorkerPool extends EventEmitter {\n  constructor(numThreads) {\n    super();\n    this.numThreads = numThreads;\n    this.workers = [];\n    this.freeWorkers = [];\n    this.tasks = [];\n\n    for (let i = 0; i < numThreads; i++)\n      this.addNewWorker();\n\n    // Any time the kWorkerFreedEvent is emitted, dispatch\n    // the next task pending in the queue, if any.\n    this.on(kWorkerFreedEvent, () => {\n      if (this.tasks.length > 0) {\n        const { task, callback } = this.tasks.shift();\n        this.runTask(task, callback);\n      }\n    });\n  }\n\n  addNewWorker() {\n    const worker = new Worker(new URL('task_processor.js', import.meta.url));\n    worker.on('message', (result) => {\n      // In case of success: Call the callback that was passed to `runTask`,\n      // remove the `TaskInfo` associated with the Worker, and mark it as free\n      // again.\n      worker[kTaskInfo].done(null, result);\n      worker[kTaskInfo] = null;\n      this.freeWorkers.push(worker);\n      this.emit(kWorkerFreedEvent);\n    });\n    worker.on('error', (err) => {\n      // In case of an uncaught exception: Call the callback that was passed to\n      // `runTask` with the error.\n      if (worker[kTaskInfo])\n        worker[kTaskInfo].done(err, null);\n      else\n        this.emit('error', err);\n      // Remove the worker from the list and start a new Worker to replace the\n      // current one.\n      this.workers.splice(this.workers.indexOf(worker), 1);\n      this.addNewWorker();\n    });\n    this.workers.push(worker);\n    this.freeWorkers.push(worker);\n    this.emit(kWorkerFreedEvent);\n  }\n\n  runTask(task, callback) {\n    if (this.freeWorkers.length === 0) {\n      // No free threads, wait until a worker thread becomes free.\n      this.tasks.push({ task, callback });\n      return;\n    }\n\n    const worker = this.freeWorkers.pop();\n    worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);\n    worker.postMessage(task);\n  }\n\n  close() {\n    for (const worker of this.workers) worker.terminate();\n  }\n}\n
\n
const { AsyncResource } = require('node:async_hooks');\nconst { EventEmitter } = require('node:events');\nconst path = require('node:path');\nconst { Worker } = require('node:worker_threads');\n\nconst kTaskInfo = Symbol('kTaskInfo');\nconst kWorkerFreedEvent = Symbol('kWorkerFreedEvent');\n\nclass WorkerPoolTaskInfo extends AsyncResource {\n  constructor(callback) {\n    super('WorkerPoolTaskInfo');\n    this.callback = callback;\n  }\n\n  done(err, result) {\n    this.runInAsyncScope(this.callback, null, err, result);\n    this.emitDestroy();  // `TaskInfo`s are used only once.\n  }\n}\n\nclass WorkerPool extends EventEmitter {\n  constructor(numThreads) {\n    super();\n    this.numThreads = numThreads;\n    this.workers = [];\n    this.freeWorkers = [];\n    this.tasks = [];\n\n    for (let i = 0; i < numThreads; i++)\n      this.addNewWorker();\n\n    // Any time the kWorkerFreedEvent is emitted, dispatch\n    // the next task pending in the queue, if any.\n    this.on(kWorkerFreedEvent, () => {\n      if (this.tasks.length > 0) {\n        const { task, callback } = this.tasks.shift();\n        this.runTask(task, callback);\n      }\n    });\n  }\n\n  addNewWorker() {\n    const worker = new Worker(path.resolve(__dirname, 'task_processor.js'));\n    worker.on('message', (result) => {\n      // In case of success: Call the callback that was passed to `runTask`,\n      // remove the `TaskInfo` associated with the Worker, and mark it as free\n      // again.\n      worker[kTaskInfo].done(null, result);\n      worker[kTaskInfo] = null;\n      this.freeWorkers.push(worker);\n      this.emit(kWorkerFreedEvent);\n    });\n    worker.on('error', (err) => {\n      // In case of an uncaught exception: Call the callback that was passed to\n      // `runTask` with the error.\n      if (worker[kTaskInfo])\n        worker[kTaskInfo].done(err, null);\n      else\n        this.emit('error', err);\n      // Remove the worker from the list and start a new Worker to replace the\n      // current one.\n      this.workers.splice(this.workers.indexOf(worker), 1);\n      this.addNewWorker();\n    });\n    this.workers.push(worker);\n    this.freeWorkers.push(worker);\n    this.emit(kWorkerFreedEvent);\n  }\n\n  runTask(task, callback) {\n    if (this.freeWorkers.length === 0) {\n      // No free threads, wait until a worker thread becomes free.\n      this.tasks.push({ task, callback });\n      return;\n    }\n\n    const worker = this.freeWorkers.pop();\n    worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);\n    worker.postMessage(task);\n  }\n\n  close() {\n    for (const worker of this.workers) worker.terminate();\n  }\n}\n\nmodule.exports = WorkerPool;\n
\n

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

\n

This pool could be used as follows:

\n
import WorkerPool from './worker_pool.js';\nimport os from 'node:os';\n\nconst pool = new WorkerPool(os.availableParallelism());\n\nlet finished = 0;\nfor (let i = 0; i < 10; i++) {\n  pool.runTask({ a: 42, b: 100 }, (err, result) => {\n    console.log(i, err, result);\n    if (++finished === 10)\n      pool.close();\n  });\n}\n
\n
const WorkerPool = require('./worker_pool.js');\nconst os = require('node:os');\n\nconst pool = new WorkerPool(os.availableParallelism());\n\nlet finished = 0;\nfor (let i = 0; i < 10; i++) {\n  pool.runTask({ a: 42, b: 100 }, (err, result) => {\n    console.log(i, err, result);\n    if (++finished === 10)\n      pool.close();\n  });\n}\n
", "displayName": "Using `AsyncResource` for a `Worker` thread pool" }, { "textRaw": "Integrating `AsyncResource` with `EventEmitter`", "name": "integrating_`asyncresource`_with_`eventemitter`", "type": "module", "desc": "

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

\n

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

\n
import { createServer } from 'node:http';\nimport { AsyncResource, executionAsyncId } from 'node:async_hooks';\n\nconst server = createServer((req, res) => {\n  req.on('close', AsyncResource.bind(() => {\n    // Execution context is bound to the current outer scope.\n  }));\n  req.on('close', () => {\n    // Execution context is bound to the scope that caused 'close' to emit.\n  });\n  res.end();\n}).listen(3000);\n
\n
const { createServer } = require('node:http');\nconst { AsyncResource, executionAsyncId } = require('node:async_hooks');\n\nconst server = createServer((req, res) => {\n  req.on('close', AsyncResource.bind(() => {\n    // Execution context is bound to the current outer scope.\n  }));\n  req.on('close', () => {\n    // Execution context is bound to the scope that caused 'close' to emit.\n  });\n  res.end();\n}).listen(3000);\n
", "displayName": "Integrating `AsyncResource` with `EventEmitter`" } ] } ], "displayName": "Asynchronous context tracking" } ] }