Async context
asyncResource.runInAsyncScope()
Invokes a function in the execution context of an AsyncResource. Useful for custom asynchronous abstractions whose callbacks lose request context. Manually owned resources should signal destruction once their lifetime ends. Tested on Node.js 22.16.0. Example output (one line per entry): ["job"].
Formal Syntax & Structure
nodejs syntaxnodejs
asyncResource.runInAsyncScope(fn[, thisArg, ...args])Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fn | Function | Callback. |
| thisArg | any | Receiver. |
| args | any[] | Callback arguments. |
Return Value
any
Callback return value.
Working Example
Example Snippetnodejs
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';const als = new AsyncLocalStorage();const resource = als.run('job', () => new AsyncResource('ByteMindJob'));try { console.log(resource.runInAsyncScope(() => als.getStore()));}finally { resource.emitDestroy(); als.disable();}