{ "source": "doc/api/async_hooks.md", "modules": [ { "textRaw": "Async Hooks", "name": "async_hooks", "introduced_in": "v8.1.0", "stability": 1, "stabilityText": "Experimental", "desc": "

The async_hooks module provides an API to register callbacks tracking the\nlifetime of asynchronous resources created inside a Node.js application.\nIt can be accessed using:

\n
const async_hooks = require('async_hooks');\n
\n", "modules": [ { "textRaw": "Terminology", "name": "terminology", "desc": "

An asynchronous resource represents an object with an associated callback.\nThis callback may be called multiple times, for example, the connection event\nin net.createServer, or just a single time like in fs.open. A resource\ncan also be closed before the callback is called. AsyncHook does not\nexplicitly distinguish between these different cases but will represent them\nas the abstract concept that is a resource.

\n", "type": "module", "displayName": "Terminology" }, { "textRaw": "Public API", "name": "public_api", "modules": [ { "textRaw": "Overview", "name": "overview", "desc": "

Following is a simple overview of the public API.

\n
const async_hooks = require('async_hooks');\n\n// Return the ID of the current execution context.\nconst eid = async_hooks.executionAsyncId();\n\n// Return the ID of the handle responsible for triggering the callback of the\n// current execution scope to call.\nconst tid = async_hooks.triggerAsyncId();\n\n// Create a new AsyncHook instance. All of these callbacks are optional.\nconst asyncHook =\n    async_hooks.createHook({ init, before, after, destroy, promiseResolve });\n\n// Allow callbacks of this AsyncHook instance to call. This is not an implicit\n// action after running the constructor, and must be explicitly run to begin\n// executing callbacks.\nasyncHook.enable();\n\n// Disable listening for new asynchronous events.\nasyncHook.disable();\n\n//\n// The following are the callbacks that can be passed to createHook().\n//\n\n// init is called during object construction. The resource may not have\n// completed construction when this callback runs, therefore all fields of the\n// resource referenced by "asyncId" may not have been populated.\nfunction init(asyncId, type, triggerAsyncId, resource) { }\n\n// before is called just before the resource's callback is called. It can be\n// called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1\n// time for requests (e.g. FSReqWrap).\nfunction before(asyncId) { }\n\n// after is called just after the resource's callback has finished.\nfunction after(asyncId) { }\n\n// destroy is called when an AsyncWrap instance is destroyed.\nfunction destroy(asyncId) { }\n\n// promiseResolve is called only for promise resources, when the\n// `resolve` function passed to the `Promise` constructor is invoked\n// (either directly or through other means of resolving a promise).\nfunction promiseResolve(asyncId) { }\n
\n", "modules": [ { "textRaw": "`async_hooks.createHook(callbacks)`", "name": "`async_hooks.createhook(callbacks)`", "meta": { "added": [ "v8.1.0" ], "changes": [] }, "desc": "\n

Registers functions to be called for different lifetime events of each async\noperation.

\n

The callbacks init()/before()/after()/destroy() are called for the\nrespective asynchronous event during a resource's lifetime.

\n

All callbacks are optional. For example, if only resource cleanup needs to\nbe tracked, then only the destroy callback needs to be passed. The\nspecifics of all functions that can be passed to callbacks is in the\nHook Callbacks section.

\n
const async_hooks = require('async_hooks');\n\nconst asyncHook = async_hooks.createHook({\n  init(asyncId, type, triggerAsyncId, resource) { },\n  destroy(asyncId) { }\n});\n
\n

Note that the callbacks will be inherited via the prototype chain:

\n
class MyAsyncCallbacks {\n  init(asyncId, type, triggerAsyncId, resource) { }\n  destroy(asyncId) {}\n}\n\nclass MyAddedCallbacks extends MyAsyncCallbacks {\n  before(asyncId) { }\n  after(asyncId) { }\n}\n\nconst asyncHook = async_hooks.createHook(new MyAddedCallbacks());\n
\n", "modules": [ { "textRaw": "Error Handling", "name": "error_handling", "desc": "

If any AsyncHook callbacks throw, the application will print the stack trace\nand exit. The exit path does follow that of an uncaught exception, but\nall uncaughtException listeners are removed, thus forcing the process to\nexit. The 'exit' callbacks will still be called unless the application is run\nwith --abort-on-uncaught-exception, in which case a stack trace will be\nprinted and the application exits, leaving a core file.

\n

The reason for this error handling behavior is that these callbacks are running\nat potentially volatile points in an object's lifetime, for example during\nclass construction and destruction. Because of this, it is deemed necessary to\nbring down the process quickly in order to prevent an unintentional abort in the\nfuture. This is subject to change in the future if a comprehensive analysis is\nperformed to ensure an exception can follow the normal control flow without\nunintentional side effects.

\n", "type": "module", "displayName": "Error Handling" }, { "textRaw": "Printing in AsyncHooks callbacks", "name": "printing_in_asynchooks_callbacks", "desc": "

Because printing to the console is an asynchronous operation, console.log()\nwill cause the AsyncHooks callbacks to be called. Using console.log() or\nsimilar asynchronous operations inside an AsyncHooks callback function will thus\ncause an infinite recursion. An easy solution to this when debugging is to use a\nsynchronous logging operation such as fs.writeSync(1, msg). This will print to\nstdout because 1 is the file descriptor for stdout and will not invoke\nAsyncHooks recursively because it is synchronous.

\n
const fs = require('fs');\nconst util = require('util');\n\nfunction debug(...args) {\n  // use a function like this one when debugging inside an AsyncHooks callback\n  fs.writeSync(1, `${util.format(...args)}\\n`);\n}\n
\n

If an asynchronous operation is needed for logging, it is possible to keep\ntrack of what caused the asynchronous operation using the information\nprovided by AsyncHooks itself. The logging should then be skipped when\nit was the logging itself that caused AsyncHooks callback to call. By\ndoing this the otherwise infinite recursion is broken.

\n", "type": "module", "displayName": "Printing in AsyncHooks callbacks" } ], "type": "module", "displayName": "`async_hooks.createHook(callbacks)`" }, { "textRaw": "`asyncHook.enable()`", "name": "`asynchook.enable()`", "desc": "\n

Enable the callbacks for a given AsyncHook instance. If no callbacks are\nprovided enabling is a noop.

\n

The AsyncHook instance is disabled by default. If the AsyncHook instance\nshould be enabled immediately after creation, the following pattern can be used.

\n
const async_hooks = require('async_hooks');\n\nconst hook = async_hooks.createHook(callbacks).enable();\n
\n", "type": "module", "displayName": "`asyncHook.enable()`" }, { "textRaw": "`asyncHook.disable()`", "name": "`asynchook.disable()`", "desc": "\n

Disable the callbacks for a given AsyncHook instance from the global pool of\nAsyncHook callbacks to be executed. Once a hook has been disabled it will not\nbe called again until enabled.

\n

For API consistency disable() also returns the AsyncHook instance.

\n", "type": "module", "displayName": "`asyncHook.disable()`" }, { "textRaw": "Hook Callbacks", "name": "hook_callbacks", "desc": "

Key events in the lifetime of asynchronous events have been categorized into\nfour areas: instantiation, before/after the callback is called, and when the\ninstance is destroyed.

\n", "modules": [ { "textRaw": "`init(asyncId, type, triggerAsyncId, resource)`", "name": "`init(asyncid,_type,_triggerasyncid,_resource)`", "desc": "\n

Called when a class is constructed that has the possibility to emit an\nasynchronous event. This does not mean the instance must call\nbefore/after before destroy is called, only that the possibility\nexists.

\n

This behavior can be observed by doing something like opening a resource then\nclosing it before the resource can be used. The following snippet demonstrates\nthis.

\n
require('net').createServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));\n
\n

Every new resource is assigned an ID that is unique within the scope of the\ncurrent process.

\n", "modules": [ { "textRaw": "`type`", "name": "`type`", "desc": "

The type is a string identifying the type of resource that caused\ninit to be called. Generally, it will correspond to the name of the\nresource's constructor.

\n
FSEVENTWRAP, FSREQWRAP, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPPARSER,\nJSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP, SHUTDOWNWRAP,\nSIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVER, TCPWRAP, TIMERWRAP, TTYWRAP,\nUDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,\nRANDOMBYTESREQUEST, TLSWRAP, Timeout, Immediate, TickObject\n
\n

There is also the PROMISE resource type, which is used to track Promise\ninstances and asynchronous work scheduled by them.

\n

Users are able to define their own type when using the public embedder API.

\n

Note: It is possible to have type name collisions. Embedders are encouraged\nto use unique prefixes, such as the npm package name, to prevent collisions\nwhen listening to the hooks.

\n", "type": "module", "displayName": "`type`" }, { "textRaw": "`triggerId`", "name": "`triggerid`", "desc": "

triggerAsyncId is the asyncId of the resource that caused (or "triggered")\nthe new resource to initialize and that caused init to call. This is different\nfrom async_hooks.executionAsyncId() that only shows when a resource was\ncreated, while triggerAsyncId shows why a resource was created.

\n

The following is a simple demonstration of triggerAsyncId:

\n
async_hooks.createHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = async_hooks.executionAsyncId();\n    fs.writeSync(\n      1, `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  }\n}).enable();\n\nrequire('net').createServer((conn) => {}).listen(8080);\n
\n

Output when hitting the server with nc localhost 8080:

\n
TCPSERVERWRAP(2): trigger: 1 execution: 1\nTCPWRAP(4): trigger: 2 execution: 0\n
\n

The TCPSERVERWRAP is the server which receives the connections.

\n

The TCPWRAP is the new connection from the client. When a new\nconnection is made the TCPWrap instance is immediately constructed. This\nhappens outside of any JavaScript stack (side note: a executionAsyncId() of \n0 means it's being executed from C++, with no JavaScript stack above it).\nWith only that information, it would be impossible to link resources together in\nterms of what caused them to be created, so triggerAsyncId is given the task \nof propagating what resource is responsible for the new resource's existence.

\n", "type": "module", "displayName": "`triggerId`" }, { "textRaw": "`resource`", "name": "`resource`", "desc": "

resource is an object that represents the actual async resource that has\nbeen initialized. This can contain useful information that can vary based on\nthe value of type. For instance, for the GETADDRINFOREQWRAP resource type,\nresource provides the hostname used when looking up the IP address for the\nhostname in net.Server.listen(). The API for accessing this information is\ncurrently not considered public, but using the Embedder API, users can provide\nand document their own resource objects. For example, such a resource object\ncould contain the SQL query being executed.

\n

In the case of Promises, the resource object will have promise property\nthat refers to the Promise that is being initialized, and a isChainedPromise\nproperty, set to true if the promise has a parent promise, and false\notherwise. For example, in the case of b = a.then(handler), a is considered\na parent Promise of b. Here, b is considered a chained promise.

\n

In some cases the resource object is reused for performance reasons, it is\nthus not safe to use it as a key in a WeakMap or add properties to it.

\n", "type": "module", "displayName": "`resource`" }, { "textRaw": "Asynchronous context example", "name": "asynchronous_context_example", "desc": "

The following is an example with additional information about the calls to\ninit between the before and after calls, specifically what the\ncallback to listen() will look like. The output formatting is slightly more\nelaborate to make calling context easier to see.

\n
let indent = 0;\nasync_hooks.createHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = async_hooks.executionAsyncId();\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(\n      1,\n      `${indentStr}${type}(${asyncId}):` +\n      ` trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n  before(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(1, `${indentStr}before:  ${asyncId}\\n`);\n    indent += 2;\n  },\n  after(asyncId) {\n    indent -= 2;\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(1, `${indentStr}after:   ${asyncId}\\n`);\n  },\n  destroy(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(1, `${indentStr}destroy: ${asyncId}\\n`);\n  },\n}).enable();\n\nrequire('net').createServer(() => {}).listen(8080, () => {\n  // Let's wait 10ms before logging the server started.\n  setTimeout(() => {\n    console.log('>>>', async_hooks.executionAsyncId());\n  }, 10);\n});\n
\n

Output from only starting the server:

\n
TCPSERVERWRAP(2): trigger: 1 execution: 1\nTickObject(3): trigger: 2 execution: 1\nbefore:  3\n  Timeout(4): trigger: 3 execution: 3\n  TIMERWRAP(5): trigger: 3 execution: 3\nafter:   3\ndestroy: 3\nbefore:  5\n  before:  4\n    TTYWRAP(6): trigger: 4 execution: 4\n    SIGNALWRAP(7): trigger: 4 execution: 4\n    TTYWRAP(8): trigger: 4 execution: 4\n>>> 4\n    TickObject(9): trigger: 4 execution: 4\n  after:   4\nafter:   5\nbefore:  9\nafter:   9\ndestroy: 4\ndestroy: 9\ndestroy: 5\n
\n

As illustrated in the example, executionAsyncId() and execution each specify\nthe value of the current execution context; which is delineated by calls to\nbefore and after.

\n

Only using execution to graph resource allocation results in the following:

\n
TTYWRAP(6) -> Timeout(4) -> TIMERWRAP(5) -> TickObject(3) -> root(1)\n
\n

The TCPSERVERWRAP is not part of this graph, even though it was the reason for\nconsole.log() being called. This is because binding to a port without a\nhostname is a synchronous operation, but to maintain a completely asynchronous\nAPI the user's callback is placed in a process.nextTick().

\n

The graph only shows when a resource was created, not why, so to track\nthe why use triggerAsyncId.

\n", "type": "module", "displayName": "Asynchronous context example" } ], "type": "module", "displayName": "`init(asyncId, type, triggerAsyncId, resource)`" }, { "textRaw": "`before(asyncId)`", "name": "`before(asyncid)`", "desc": "\n

When an asynchronous operation is initiated (such as a TCP server receiving a\nnew connection) or completes (such as writing data to disk) a callback is\ncalled to notify the user. The before callback is called just before said\ncallback is executed. asyncId is the unique identifier assigned to the\nresource about to execute the callback.

\n

The before callback will be called 0 to N times. The before callback\nwill typically be called 0 times if the asynchronous operation was cancelled\nor, for example, if no connections are received by a TCP server. Persistent\nasynchronous resources like a TCP server will typically call the before\ncallback multiple times, while other operations like fs.open() will call\nit only once.

\n", "type": "module", "displayName": "`before(asyncId)`" }, { "textRaw": "`after(asyncId)`", "name": "`after(asyncid)`", "desc": "\n

Called immediately after the callback specified in before is completed.

\n

Note: If an uncaught exception occurs during execution of the callback, then\nafter will run after the 'uncaughtException' event is emitted or a\ndomain's handler runs.

\n", "type": "module", "displayName": "`after(asyncId)`" }, { "textRaw": "`destroy(asyncId)`", "name": "`destroy(asyncid)`", "desc": "\n

Called after the resource corresponding to asyncId is destroyed. It is also\ncalled asynchronously from the embedder API emitDestroy().

\n

Note: Some resources depend on garbage collection for cleanup, so if a\nreference is made to the resource object passed to init it is possible that\ndestroy will never be called, causing a memory leak in the application. If\nthe resource does not depend on garbage collection, then this will not be an\nissue.

\n", "type": "module", "displayName": "`destroy(asyncId)`" }, { "textRaw": "`promiseResolve(asyncId)`", "name": "`promiseresolve(asyncid)`", "desc": "\n

Called when the resolve function passed to the Promise constructor is\ninvoked (either directly or through other means of resolving a promise).

\n

Note that resolve() does not do any observable synchronous work.

\n

Note: This does not necessarily mean that the Promise is fulfilled or\nrejected at this point, if the Promise was resolved by assuming the state\nof another Promise.

\n
new Promise((resolve) => resolve(true)).then((a) => {});\n
\n

calls the following callbacks:

\n
init for PROMISE with id 5, trigger id: 1\n  promise resolve 5      # corresponds to resolve(true)\ninit for PROMISE with id 6, trigger id: 5  # the Promise returned by then()\n  before 6               # the then() callback is entered\n  promise resolve 6      # the then() callback resolves the promise by returning\n  after 6\n
\n", "type": "module", "displayName": "`promiseResolve(asyncId)`" } ], "type": "module", "displayName": "Hook Callbacks" }, { "textRaw": "`async_hooks.executionAsyncId()`", "name": "`async_hooks.executionasyncid()`", "meta": { "added": [ "v8.1.0" ], "changes": [ { "version": "v8.2.0", "pr-url": "https://github.com/nodejs/node/pull/13490", "description": "Renamed from currentId" } ] }, "desc": "\n
const async_hooks = require('async_hooks');\n\nconsole.log(async_hooks.executionAsyncId());  // 1 - bootstrap\nfs.open(path, 'r', (err, fd) => {\n  console.log(async_hooks.executionAsyncId());  // 6 - open()\n});\n
\n

The ID returned from executionAsyncId() is related to execution timing, not\ncausality (which is covered by triggerAsyncId()):

\n
const server = net.createServer(function onConnection(conn) {\n  // Returns the ID of the server, not of the new connection, because the\n  // onConnection callback runs in the execution scope of the server's\n  // MakeCallback().\n  async_hooks.executionAsyncId();\n\n}).listen(port, function onListening() {\n  // Returns the ID of a TickObject (i.e. process.nextTick()) because all\n  // callbacks passed to .listen() are wrapped in a nextTick().\n  async_hooks.executionAsyncId();\n});\n
\n

Note that promise contexts may not get precise executionAsyncIds by default.\nSee the section on promise execution tracking.

\n", "type": "module", "displayName": "`async_hooks.executionAsyncId()`" }, { "textRaw": "`async_hooks.triggerAsyncId()`", "name": "`async_hooks.triggerasyncid()`", "desc": "\n
const server = net.createServer((conn) => {\n  // The resource that caused (or triggered) this callback to be called\n  // was that of the new connection. Thus the return value of triggerAsyncId()\n  // is the asyncId of "conn".\n  async_hooks.triggerAsyncId();\n\n}).listen(port, () => {\n  // Even though all callbacks passed to .listen() are wrapped in a nextTick()\n  // the callback itself exists because the call to the server's .listen()\n  // was made. So the return value would be the ID of the server.\n  async_hooks.triggerAsyncId();\n});\n
\n

Note that promise contexts may not get valid triggerAsyncIds by default. See\nthe section on promise execution tracking.

\n", "type": "module", "displayName": "`async_hooks.triggerAsyncId()`" } ], "type": "module", "displayName": "Overview" } ], "type": "module", "displayName": "Public API" }, { "textRaw": "Promise execution tracking", "name": "promise_execution_tracking", "desc": "

By default, promise executions are not assigned asyncIds due to the relatively\nexpensive nature of the promise introspection API provided by\nV8. This means that programs using promises or async/await will not get\ncorrect execution and trigger ids for promise callback contexts by default.

\n

Here's an example:

\n
const ah = require('async_hooks');\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0\n
\n

Observe that the then callback claims to have executed in the context of the\nouter scope even though there was an asynchronous hop involved. Also note that\nthe triggerAsyncId value is 0, which means that we are missing context about the\nresource that caused (triggered) the then callback to be executed.

\n

Installing async hooks via async_hooks.createHook enables promise execution\ntracking. Example:

\n
const ah = require('async_hooks');\nah.createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);\n});\n// produces:\n// eid 7 tid 6\n
\n

In this example, adding any actual hook function enabled the tracking of\npromises. There are two promises in the example above; the promise created by\nPromise.resolve() and the promise returned by the call to then. In the\nexample above, the first promise got the asyncId 6 and the latter got asyncId 7.\nDuring the execution of the then callback, we are executing in the context of\npromise with asyncId 7. This promise was triggered by async resource 6.

\n

Another subtlety with promises is that before and after callbacks are run\nonly on chained promises. That means promises not created by then/catch will\nnot have the before and after callbacks fired on them. For more details see\nthe details of the V8 PromiseHooks API.

\n", "type": "module", "displayName": "Promise execution tracking" }, { "textRaw": "JavaScript Embedder API", "name": "javascript_embedder_api", "desc": "

Library developers that handle their own asynchronous resources performing tasks\nlike I/O, connection pooling, or managing callback queues may use the \nAsyncWrap JavaScript API so that all the appropriate callbacks are called.

\n", "modules": [ { "textRaw": "`class AsyncResource()`", "name": "`class_asyncresource()`", "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
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\n// Call AsyncHooks before callbacks.\n// Deprecated: Use asyncResource.runInAsyncScope instead.\nasyncResource.emitBefore();\n\n// Call AsyncHooks after callbacks.\n// Deprecated: Use asyncResource.runInAsyncScope instead.\nasyncResource.emitAfter();\n
\n", "modules": [ { "textRaw": "`AsyncResource(type[, options])`", "name": "`asyncresource(type[,_options])`", "desc": "\n

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
\n", "type": "module", "displayName": "`AsyncResource(type[, options])`" }, { "textRaw": "`asyncResource.runInAsyncScope(fn[, thisArg, ...args])`", "name": "`asyncresource.runinasyncscope(fn[,_thisarg,_...args])`", "meta": { "added": [ "v9.6.0" ], "changes": [] }, "desc": "\n

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.

\n", "type": "module", "displayName": "`asyncResource.runInAsyncScope(fn[, thisArg, ...args])`" }, { "textRaw": "`asyncResource.emitBefore()`", "name": "`asyncresource.emitbefore()`", "meta": { "deprecated": [ "v9.6.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`asyncResource.runInAsyncScope()`][] instead.", "desc": "

Call all before callbacks to notify that a new asynchronous execution context\nis being entered. If nested calls to emitBefore() are made, the stack of\nasyncIds will be tracked and properly unwound.

\n

before and after calls must be unwound in the same order that they\nare called. Otherwise, an unrecoverable exception will occur and the process\nwill abort. For this reason, the emitBefore and emitAfter APIs are\nconsidered deprecated. Please use runInAsyncScope, as it provides a much safer\nalternative.

\n", "type": "module", "displayName": "`asyncResource.emitBefore()`" }, { "textRaw": "`asyncResource.emitAfter()`", "name": "`asyncresource.emitafter()`", "meta": { "deprecated": [ "v9.6.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`asyncResource.runInAsyncScope()`][] instead.", "desc": "

Call all after callbacks. If nested calls to emitBefore() were made, then\nmake sure the stack is unwound properly. Otherwise an error will be thrown.

\n

If the user's callback throws an exception, emitAfter() will automatically be\ncalled for all asyncIds on the stack if the error is handled by a domain or\n'uncaughtException' handler.

\n

before and after calls must be unwound in the same order that they\nare called. Otherwise, an unrecoverable exception will occur and the process\nwill abort. For this reason, the emitBefore and emitAfter APIs are\nconsidered deprecated. Please use runInAsyncScope, as it provides a much safer\nalternative.

\n", "type": "module", "displayName": "`asyncResource.emitAfter()`" }, { "textRaw": "`asyncResource.emitDestroy()`", "name": "`asyncresource.emitdestroy()`", "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.

\n", "type": "module", "displayName": "`asyncResource.emitDestroy()`" }, { "textRaw": "`asyncResource.asyncId()`", "name": "`asyncResource.asyncId()`", "desc": "\n", "type": "module", "displayName": "`asyncResource.triggerAsyncId()`" }, { "textRaw": "`asyncResource.triggerAsyncId()`", "name": "`asyncresource.triggerasyncid()`", "desc": "\n", "type": "module", "displayName": "`asyncResource.triggerAsyncId()`" } ], "type": "module", "displayName": "`class AsyncResource()`" } ], "type": "module", "displayName": "JavaScript Embedder API" } ], "type": "module", "displayName": "Async Hooks" } ] }