{
  "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": "<p>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.</p>\n<p>The <code>AsyncLocalStorage</code> and <code>AsyncResource</code> classes are part of the\n<code>node:async_hooks</code> module:</p>\n<pre><code class=\"language-mjs\">import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';\n</code></pre>\n<pre><code class=\"language-cjs\">const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');\n</code></pre>",
          "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": "<p>This class creates stores that stay coherent through asynchronous operations.</p>\n<p>While you can create your own implementation on top of the <code>node:async_hooks</code>\nmodule, <code>AsyncLocalStorage</code> should be preferred as it is a performant and memory\nsafe implementation that involves significant optimizations that are non-obvious\nto implement.</p>\n<p>The following example uses <code>AsyncLocalStorage</code> to build a simple logger\nthat assigns IDs to incoming HTTP requests and includes them in messages\nlogged within each request.</p>\n<pre><code class=\"language-mjs\">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</code></pre>\n<pre><code class=\"language-cjs\">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</code></pre>\n<p>Each instance of <code>AsyncLocalStorage</code> maintains an independent storage context.\nMultiple instances can safely exist simultaneously without risk of interfering\nwith each other's data.</p>",
          "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": "<p>Creates a new instance of <code>AsyncLocalStorage</code>. Store is only provided within a\n<code>run()</code> call or after an <code>enterWith()</code> call.</p>"
            }
          ],
          "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": "<p>Binds the given function to the current execution context.</p>"
            },
            {
              "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": "<p>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.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple\nasync context tracking purposes, for example:</p>\n<pre><code class=\"language-js\">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</code></pre>"
            }
          ],
          "methods": [
            {
              "textRaw": "`asyncLocalStorage.disable()`",
              "name": "disable",
              "type": "method",
              "meta": {
                "added": [
                  "v13.10.0",
                  "v12.17.0"
                ],
                "changes": []
              },
              "stability": 1,
              "stabilityText": "Experimental",
              "signatures": [
                {
                  "params": []
                }
              ],
              "desc": "<p>Disables the instance of <code>AsyncLocalStorage</code>. All subsequent calls\nto <code>asyncLocalStorage.getStore()</code> will return <code>undefined</code> until\n<code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code> is called again.</p>\n<p>When calling <code>asyncLocalStorage.disable()</code>, all current contexts linked to the\ninstance will be exited.</p>\n<p>Calling <code>asyncLocalStorage.disable()</code> is required before the\n<code>asyncLocalStorage</code> can be garbage collected. This does not apply to stores\nprovided by the <code>asyncLocalStorage</code>, as those objects are garbage collected\nalong with the corresponding async resources.</p>\n<p>Use this method when the <code>asyncLocalStorage</code> is not in use anymore\nin the current process.</p>"
            },
            {
              "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": "<p>Returns the current store.\nIf called outside of an asynchronous context initialized by\ncalling <code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code>, it\nreturns <code>undefined</code>.</p>"
            },
            {
              "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": "<p>Transitions into the context for the remainder of the current\nsynchronous execution and then persists the store through any following\nasynchronous calls.</p>\n<p>Example:</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>This transition will continue for the <em>entire</em> 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 <code>AsyncResource</code>. That is why\n<code>run()</code> should be preferred over <code>enterWith()</code> unless there are strong reasons\nto use the latter method.</p>\n<pre><code class=\"language-js\">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</code></pre>"
            },
            {
              "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": "<p>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.</p>\n<p>The optional <code>args</code> are passed to the callback function.</p>\n<p>If the callback function throws an error, the error is thrown by <code>run()</code> too.\nThe stacktrace is not impacted by this call and the context is exited.</p>\n<p>Example:</p>\n<pre><code class=\"language-js\">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</code></pre>"
            },
            {
              "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": "<p>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 <code>getStore()</code>\ncall done within the callback function will always return <code>undefined</code>.</p>\n<p>The optional <code>args</code> are passed to the callback function.</p>\n<p>If the callback function throws an error, the error is thrown by <code>exit()</code> too.\nThe stacktrace is not impacted by this call and the context is re-entered.</p>\n<p>Example:</p>\n<pre><code class=\"language-js\">// 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</code></pre>"
            },
            {
              "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": "<p>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 (<code>using</code> syntax).</p>\n<p>Example:</p>\n<pre><code class=\"language-mjs\">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</code></pre>\n<pre><code class=\"language-cjs\">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</code></pre>\n<p>The <code>withScope()</code> 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.</p>\n<pre><code class=\"language-mjs\">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</code></pre>\n<pre><code class=\"language-cjs\">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</code></pre>\n<p><strong>Important:</strong> When using <code>withScope()</code> in async functions before the first\n<code>await</code>, be aware that the scope change will affect the caller's context. The\nsynchronous portion of an async function (before the first <code>await</code>) runs\nimmediately when called, and when it reaches the first <code>await</code>, 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 <code>run()</code> which\nproperly isolates context across async boundaries.</p>\n<pre><code class=\"language-mjs\">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</code></pre>"
            }
          ],
          "properties": [
            {
              "textRaw": "Type: {string}",
              "name": "name",
              "type": "string",
              "meta": {
                "added": [
                  "v24.0.0"
                ],
                "changes": []
              },
              "desc": "<p>The name of the <code>AsyncLocalStorage</code> instance if provided.</p>"
            }
          ],
          "modules": [
            {
              "textRaw": "Usage with `async/await`",
              "name": "usage_with_`async/await`",
              "type": "module",
              "desc": "<p>If, within an async function, only one <code>await</code> call is to run within a context,\nthe following pattern should be used:</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>In this example, the store is only available in the callback function and the\nfunctions called by <code>foo</code>. Outside of <code>run</code>, calling <code>getStore</code> will return\n<code>undefined</code>.</p>",
              "displayName": "Usage with `async/await`"
            },
            {
              "textRaw": "Troubleshooting: Context loss",
              "name": "troubleshooting:_context_loss",
              "type": "module",
              "desc": "<p>In most cases, <code>AsyncLocalStorage</code> works without issues. In rare situations, the\ncurrent store is lost in one of the asynchronous operations.</p>\n<p>If your code is callback-based, it is enough to promisify it with\n<a href=\"util.html#utilpromisifyoriginal\"><code>util.promisify()</code></a> so it starts working with native promises.</p>\n<p>If you need to use a callback-based API or your code assumes\na custom thenable implementation, use the <a href=\"#class-asyncresource\"><code>AsyncResource</code></a> 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 <code>asyncLocalStorage.getStore()</code> after the calls you suspect are responsible\nfor the loss. When the code logs <code>undefined</code>, the last callback called is\nprobably responsible for the context loss.</p>",
              "displayName": "Troubleshooting: Context loss"
            }
          ]
        },
        {
          "textRaw": "Class: `RunScope`",
          "name": "RunScope",
          "type": "class",
          "meta": {
            "added": [
              "v25.9.0"
            ],
            "changes": []
          },
          "stability": 1,
          "stabilityText": "Experimental",
          "desc": "<p>A disposable scope returned by <a href=\"#asynclocalstoragewithscopestore\"><code>asyncLocalStorage.withScope()</code></a> that\nautomatically restores the previous store value when disposed. This class\nimplements the <a href=\"https://github.com/tc39/proposal-explicit-resource-management\">Explicit Resource Management</a> protocol and is designed to work\nwith JavaScript's <code>using</code> syntax.</p>\n<p>The scope automatically restores the previous store value when the <code>using</code> block\nexits, whether through normal completion or by throwing an error.</p>",
          "methods": [
            {
              "textRaw": "`scope.dispose()`",
              "name": "dispose",
              "type": "method",
              "meta": {
                "added": [
                  "v25.9.0"
                ],
                "changes": []
              },
              "signatures": [
                {
                  "params": []
                }
              ],
              "desc": "<p>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.</p>\n<p>The <code>[Symbol.dispose]()</code> method defers to <code>dispose()</code>.</p>\n<p>If <code>withScope()</code> is called without the <code>using</code> keyword, <code>dispose()</code> must be\ncalled manually to restore the previous store value. Forgetting to call\n<code>dispose()</code> will cause the store value to persist for the remainder of the\ncurrent execution context:</p>\n<pre><code class=\"language-mjs\">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</code></pre>\n<pre><code class=\"language-cjs\">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</code></pre>"
            }
          ]
        },
        {
          "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": "<p>The class <code>AsyncResource</code> is designed to be extended by the embedder's async\nresources. Using this, users can easily trigger the lifetime events of their\nown resources.</p>\n<p>The <code>init</code> hook will trigger when an <code>AsyncResource</code> is instantiated.</p>\n<p>The following is an overview of the <code>AsyncResource</code> API.</p>\n<pre><code class=\"language-mjs\">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</code></pre>\n<pre><code class=\"language-cjs\">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</code></pre>",
          "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": "<p>Example usage:</p>\n<pre><code class=\"language-js\">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</code></pre>"
            }
          ],
          "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": "<p>Binds the given function to the current execution context.</p>"
            }
          ],
          "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": "<p>Binds the given function to execute to this <code>AsyncResource</code>'s scope.</p>"
            },
            {
              "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": "<p>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.</p>"
            },
            {
              "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": "<p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will\nbe thrown if it is called more than once. This <strong>must</strong> be manually called. If\nthe resource is left to be collected by the GC then the <code>destroy</code> hooks will\nnever be called.</p>"
            },
            {
              "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": "<p><a id=\"async-resource-worker-pool\"></a></p>"
            }
          ],
          "modules": [
            {
              "textRaw": "Using `AsyncResource` for a `Worker` thread pool",
              "name": "using_`asyncresource`_for_a_`worker`_thread_pool",
              "type": "module",
              "desc": "<p>The following example shows how to use the <code>AsyncResource</code> class to properly\nprovide async tracking for a <a href=\"worker_threads.html#class-worker\"><code>Worker</code></a> pool. Other resource pools, such as\ndatabase connection pools, can follow a similar model.</p>\n<p>Assuming that the task is adding two numbers, using a file named\n<code>task_processor.js</code> with the following content:</p>\n<pre><code class=\"language-mjs\">import { parentPort } from 'node:worker_threads';\nparentPort.on('message', (task) => {\n  parentPort.postMessage(task.a + task.b);\n});\n</code></pre>\n<pre><code class=\"language-cjs\">const { parentPort } = require('node:worker_threads');\nparentPort.on('message', (task) => {\n  parentPort.postMessage(task.a + task.b);\n});\n</code></pre>\n<p>a Worker pool around it could use the following structure:</p>\n<pre><code class=\"language-mjs\">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 &#x3C; 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</code></pre>\n<pre><code class=\"language-cjs\">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 &#x3C; 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</code></pre>\n<p>Without the explicit tracking added by the <code>WorkerPoolTaskInfo</code> objects,\nit would appear that the callbacks are associated with the individual <code>Worker</code>\nobjects. However, the creation of the <code>Worker</code>s is not associated with the\ncreation of the tasks and does not provide information about when tasks\nwere scheduled.</p>\n<p>This pool could be used as follows:</p>\n<pre><code class=\"language-mjs\">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 &#x3C; 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</code></pre>\n<pre><code class=\"language-cjs\">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 &#x3C; 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</code></pre>",
              "displayName": "Using `AsyncResource` for a `Worker` thread pool"
            },
            {
              "textRaw": "Integrating `AsyncResource` with `EventEmitter`",
              "name": "integrating_`asyncresource`_with_`eventemitter`",
              "type": "module",
              "desc": "<p>Event listeners triggered by an <a href=\"events.html#class-eventemitter\"><code>EventEmitter</code></a> may be run in a different\nexecution context than the one that was active when <code>eventEmitter.on()</code> was\ncalled.</p>\n<p>The following example shows how to use the <code>AsyncResource</code> class to properly\nassociate an event listener with the correct execution context. The same\napproach can be applied to a <a href=\"stream.html#stream\"><code>Stream</code></a> or a similar event-driven class.</p>\n<pre><code class=\"language-mjs\">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</code></pre>\n<pre><code class=\"language-cjs\">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</code></pre>",
              "displayName": "Integrating `AsyncResource` with `EventEmitter`"
            }
          ]
        }
      ],
      "displayName": "Asynchronous context tracking"
    }
  ]
}