{ "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": "<p><strong>Source Code:</strong> <a href=\"https://github.com/nodejs/node/blob/v18.20.1/lib/async_hooks.js\">lib/async_hooks.js</a></p>", "modules": [ { "textRaw": "Introduction", "name": "introduction", "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>", "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": "<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// 1: start\n// 0: finish\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// 1: start\n// 0: finish\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>", "classMethods": [ { "textRaw": "Static method: `AsyncLocalStorage.bind(fn)`", "type": "classMethod", "name": "bind", "meta": { "added": [ "v18.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "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." }, "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." } ] } ], "desc": "<p>Binds the given function to the current execution context.</p>" }, { "textRaw": "Static method: `AsyncLocalStorage.snapshot()`", "type": "classMethod", "name": "snapshot", "meta": { "added": [ "v18.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "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`." }, "params": [] } ], "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()`", "type": "method", "name": "disable", "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()`", "type": "method", "name": "getStore", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {any}", "name": "return", "type": "any" }, "params": [] } ], "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)`", "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": "<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])`", "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": "<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])`", "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": "<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>" } ], "modules": [ { "textRaw": "Usage with `async/await`", "name": "usage_with_`async/await`", "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>", "type": "module", "displayName": "Usage with `async/await`" }, { "textRaw": "Troubleshooting: Context loss", "name": "troubleshooting:_context_loss", "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>", "type": "module", "displayName": "Troubleshooting: Context loss" } ], "signatures": [ { "params": [], "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>" } ] }, { "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": "<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>", "classMethods": [ { "textRaw": "Static method: `AsyncResource.bind(fn[, type[, thisArg]])`", "type": "classMethod", "name": "bind", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [ { "version": "v17.8.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`." }, { "textRaw": "`thisArg` {any}", "name": "thisArg", "type": "any" } ] } ], "desc": "<p>Binds the given function to the current execution context.</p>\n<p>The returned function will have an <code>asyncResource</code> property referencing\nthe <code>AsyncResource</code> to which the function is bound.</p>" } ], "methods": [ { "textRaw": "`asyncResource.bind(fn[, thisArg])`", "type": "method", "name": "bind", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [ { "version": "v17.8.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" } ] } ], "desc": "<p>Binds the given function to execute to this <code>AsyncResource</code>'s scope.</p>\n<p>The returned function will have an <code>asyncResource</code> property referencing\nthe <code>AsyncResource</code> to which the function is bound.</p>" }, { "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": "<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()`", "type": "method", "name": "emitDestroy", "signatures": [ { "return": { "textRaw": "Returns: {AsyncResource} A reference to `asyncResource`.", "name": "return", "type": "AsyncResource", "desc": "A reference to `asyncResource`." }, "params": [] } ], "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()`", "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": "<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", "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 path from 'node:path';\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</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 < 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 < 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 < 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>", "type": "module", "displayName": "Using `AsyncResource` for a `Worker` thread pool" }, { "textRaw": "Integrating `AsyncResource` with `EventEmitter`", "name": "integrating_`asyncresource`_with_`eventemitter`", "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>", "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": "<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>" } ] } ], "type": "module", "displayName": "Asynchronous context tracking" } ] }