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

Source Code: lib/async_hooks.js

", "modules": [ { "textRaw": "Introduction", "name": "introduction", "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\nasync_hooks module:

\n
import async_hooks from 'async_hooks';\n
\n
const async_hooks = require('async_hooks');\n
", "type": "module", "displayName": "Introduction" } ], "classes": [ { "textRaw": "Class: `AsyncLocalStorage`", "type": "class", "name": "AsyncLocalStorage", "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 async_hooks module,\nAsyncLocalStorage should be preferred as it is a performant and memory safe\nimplementation that involves significant optimizations that are non-obvious to\nimplement.

\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 'http';\nimport { AsyncLocalStorage } from '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//   1: start\n//   0: finish\n//   1: finish\n
\n
const http = require('http');\nconst { AsyncLocalStorage } = require('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//   1: start\n//   0: finish\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 data.

", "methods": [ { "textRaw": "`asyncLocalStorage.disable()`", "type": "method", "name": "disable", "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()`", "type": "method", "name": "getStore", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {any}", "name": "return", "type": "any" }, "params": [] } ], "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)`", "type": "method", "name": "enterWith", "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])`", "type": "method", "name": "run", "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" } ] } ], "desc": "

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

\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    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])`", "type": "method", "name": "exit", "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" } ] } ], "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
" } ], "modules": [ { "textRaw": "Usage with `async/await`", "name": "usage_with_`async/await`", "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.

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

In most cases your application or library code should have no issues with\nAsyncLocalStorage. But in rare cases you may face situations when the\ncurrent store is lost in one of the asynchronous operations. In those cases,\nconsider the following options.

\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 keep using 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. To\ndo so, you will need to identify the function call responsible for the\ncontext loss. You can do that by logging the content of\nasyncLocalStorage.getStore() after the calls you suspect are responsible for\nthe loss. When the code logs undefined, the last callback called is probably\nresponsible for the context loss.

", "type": "module", "displayName": "Troubleshooting: Context loss" } ], "signatures": [ { "params": [], "desc": "

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

" } ] }, { "textRaw": "Class: `AsyncResource`", "type": "class", "name": "AsyncResource", "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 '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('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
", "classMethods": [ { "textRaw": "Static method: `AsyncResource.bind(fn[, type, [thisArg]])`", "type": "classMethod", "name": "bind", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [ { "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`." }, { "textRaw": "`thisArg` {any}", "name": "thisArg", "type": "any" } ] } ], "desc": "

Binds the given function to the current execution context.

\n

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

" } ], "methods": [ { "textRaw": "`asyncResource.bind(fn[, thisArg])`", "type": "method", "name": "bind", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [ { "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" } ] } ], "desc": "

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

\n

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

" }, { "textRaw": "`asyncResource.runInAsyncScope(fn[, thisArg, ...args])`", "type": "method", "name": "runInAsyncScope", "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." }, { "textRaw": "`...args` {any} Optional arguments to pass to the function.", "name": "...args", "type": "any", "desc": "Optional arguments to pass to the function." } ] } ], "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()`", "type": "method", "name": "emitDestroy", "signatures": [ { "return": { "textRaw": "Returns: {AsyncResource} A reference to `asyncResource`.", "name": "return", "type": "AsyncResource", "desc": "A reference to `asyncResource`." }, "params": [] } ], "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()`", "type": "method", "name": "asyncId", "signatures": [ { "return": { "textRaw": "Returns: {number} The unique `asyncId` assigned to the resource.", "name": "return", "type": "number", "desc": "The unique `asyncId` assigned to the resource." }, "params": [] } ] }, { "textRaw": "`asyncResource.triggerAsyncId()`", "type": "method", "name": "triggerAsyncId", "signatures": [ { "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." }, "params": [] } ], "desc": "

" } ], "modules": [ { "textRaw": "Using `AsyncResource` for a `Worker` thread pool", "name": "using_`asyncresource`_for_a_`worker`_thread_pool", "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 'worker_threads';\nparentPort.on('message', (task) => {\n  parentPort.postMessage(task.a + task.b);\n});\n
\n
const { parentPort } = require('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 'async_hooks';\nimport { EventEmitter } from 'events';\nimport path from 'path';\nimport { Worker } from '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_processer.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('async_hooks');\nconst { EventEmitter } = require('events');\nconst path = require('path');\nconst { Worker } = require('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 'os';\n\nconst pool = new WorkerPool(os.cpus().length);\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('os');\n\nconst pool = new WorkerPool(os.cpus().length);\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
", "type": "module", "displayName": "Using `AsyncResource` for a `Worker` thread pool" }, { "textRaw": "Integrating `AsyncResource` with `EventEmitter`", "name": "integrating_`asyncresource`_with_`eventemitter`", "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 'http';\nimport { AsyncResource, executionAsyncId } from '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('http');\nconst { AsyncResource, executionAsyncId } = require('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
", "type": "module", "displayName": "Integrating `AsyncResource` with `EventEmitter`" } ], "signatures": [ { "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." } ] } ], "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
" } ] } ], "type": "module", "displayName": "Asynchronous Context Tracking" } ] }