/
opt
/
alt
/
alt-nodejs10
/
root
/
usr
/
share
/
doc
/
alt-nodejs10-nodejs-10.24.1
/
html
/
api
/
Upload Filee
HOME
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Async Hooks | Node.js v10.24.1 Documentation</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic"> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/sh.css"> <link rel="canonical" href="https://nodejs.org/api/async_hooks.html"> </head> <body class="alt apidoc" id="api-section-async_hooks"> <div id="content" class="clearfix"> <div id="column2" class="interior"> <div id="intro" class="interior"> <a href="/" title="Go back to the home page"> Node.js </a> </div> <ul> <li><a href="documentation.html" class="nav-documentation">About these Docs</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage & Example</a></li> </ul> <div class="line"></div> <ul> <li><a href="assert.html" class="nav-assert">Assertion Testing</a></li> <li><a href="async_hooks.html" class="nav-async_hooks active">Async Hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ Addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ Addons - N-API</a></li> <li><a href="child_process.html" class="nav-child_process">Child Processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command Line Options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="esm.html" class="nav-esm">ECMAScript Modules</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File System</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance Hooks</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query Strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String Decoder</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace Events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/Datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker Threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <div class="line"></div> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">GitHub Repo & Issue Tracker</a></li> </ul> </div> <div id="column1" data-id="async_hooks" class="interior"> <header> <h1>Node.js v10.24.1 Documentation</h1> <div id="gtoc"> <ul> <li> <a href="index.html" name="toc">Index</a> </li> <li> <a href="all.html">View on single page</a> </li> <li> <a href="async_hooks.json">View as JSON</a> </li> <li class="version-picker"> <a href="#">View another version <span>▼</span></a> <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v15.x/api/async_hooks.html">15.x</a></li> <li><a href="https://nodejs.org/docs/latest-v14.x/api/async_hooks.html">14.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v13.x/api/async_hooks.html">13.x</a></li> <li><a href="https://nodejs.org/docs/latest-v12.x/api/async_hooks.html">12.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v11.x/api/async_hooks.html">11.x</a></li> <li><a href="https://nodejs.org/docs/latest-v10.x/api/async_hooks.html">10.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v9.x/api/async_hooks.html">9.x</a></li> <li><a href="https://nodejs.org/docs/latest-v8.x/api/async_hooks.html">8.x</a></li></ol> </li> <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/async_hooks.md"><span class="github_icon"><svg height="16" width="16" viewBox="0 0 16.1 16.1" fill="currentColor"><path d="M8 0a8 8 0 0 0-2.5 15.6c.4 0 .5-.2.5-.4v-1.5c-2 .4-2.5-.5-2.7-1 0-.1-.5-.9-.8-1-.3-.2-.7-.6 0-.6.6 0 1 .6 1.2.8.7 1.2 1.9 1 2.4.7 0-.5.2-.9.5-1-1.8-.3-3.7-1-3.7-4 0-.9.3-1.6.8-2.2 0-.2-.3-1 .1-2 0 0 .7-.3 2.2.7a7.4 7.4 0 0 1 4 0c1.5-1 2.2-.8 2.2-.8.5 1.1.2 2 .1 2.1.5.6.8 1.3.8 2.2 0 3-1.9 3.7-3.6 4 .3.2.5.7.5 1.4v2.2c0 .2.1.5.5.4A8 8 0 0 0 16 8a8 8 0 0 0-8-8z"/></svg></span>Edit on GitHub</a></li> </ul> </div> <hr> </header> <div id="toc"> <h2>Table of Contents</h2> <ul> <li> <p><span class="stability_1"><a href="#async_hooks_async_hooks">Async Hooks</a></span></p> <ul> <li><a href="#async_hooks_terminology">Terminology</a></li> <li> <p><a href="#async_hooks_public_api">Public API</a></p> <ul> <li> <p><a href="#async_hooks_overview">Overview</a></p> <ul> <li> <p><a href="#async_hooks_async_hooks_createhook_callbacks">async_hooks.createHook(callbacks)</a></p> <ul> <li><a href="#async_hooks_error_handling">Error Handling</a></li> <li><a href="#async_hooks_printing_in_asynchooks_callbacks">Printing in AsyncHooks callbacks</a></li> </ul> </li> <li><a href="#async_hooks_asynchook_enable">asyncHook.enable()</a></li> <li><a href="#async_hooks_asynchook_disable">asyncHook.disable()</a></li> <li> <p><a href="#async_hooks_hook_callbacks">Hook Callbacks</a></p> <ul> <li> <p><a href="#async_hooks_init_asyncid_type_triggerasyncid_resource">init(asyncId, type, triggerAsyncId, resource)</a></p> <ul> <li><a href="#async_hooks_type"><code>type</code></a></li> <li><a href="#async_hooks_triggerasyncid"><code>triggerAsyncId</code></a></li> <li><a href="#async_hooks_resource"><code>resource</code></a></li> <li><a href="#async_hooks_asynchronous_context_example">Asynchronous context example</a></li> </ul> </li> <li><a href="#async_hooks_before_asyncid">before(asyncId)</a></li> <li><a href="#async_hooks_after_asyncid">after(asyncId)</a></li> <li><a href="#async_hooks_destroy_asyncid">destroy(asyncId)</a></li> <li><a href="#async_hooks_promiseresolve_asyncid">promiseResolve(asyncId)</a></li> </ul> </li> <li><a href="#async_hooks_async_hooks_executionasyncid">async_hooks.executionAsyncId()</a></li> <li><a href="#async_hooks_async_hooks_triggerasyncid">async_hooks.triggerAsyncId()</a></li> </ul> </li> </ul> </li> <li><a href="#async_hooks_promise_execution_tracking">Promise execution tracking</a></li> <li> <p><a href="#async_hooks_javascript_embedder_api">JavaScript Embedder API</a></p> <ul> <li> <p><a href="#async_hooks_class_asyncresource">Class: AsyncResource</a></p> <ul> <li><a href="#async_hooks_new_asyncresource_type_options">new AsyncResource(type[, options])</a></li> <li><a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args">asyncResource.runInAsyncScope(fn[, thisArg, ...args])</a></li> <li><span class="stability_0"><a href="#async_hooks_asyncresource_emitbefore">asyncResource.emitBefore()</a></span></li> <li><span class="stability_0"><a href="#async_hooks_asyncresource_emitafter">asyncResource.emitAfter()</a></span></li> <li><a href="#async_hooks_asyncresource_emitdestroy">asyncResource.emitDestroy()</a></li> <li><a href="#async_hooks_asyncresource_asyncid">asyncResource.asyncId()</a></li> <li><a href="#async_hooks_asyncresource_triggerasyncid">asyncResource.triggerAsyncId()</a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </div> <div id="apicontent"> <h1>Async Hooks<span><a class="mark" href="#async_hooks_async_hooks" id="async_hooks_async_hooks">#</a></span></h1> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>The <code>async_hooks</code> module provides an API to register callbacks tracking the lifetime of asynchronous resources created inside a Node.js application. It can be accessed using:</p> <pre><code class="language-js">const async_hooks = require('async_hooks'); </code></pre> <h2>Terminology<span><a class="mark" href="#async_hooks_terminology" id="async_hooks_terminology">#</a></span></h2> <p>An asynchronous resource represents an object with an associated callback. This callback may be called multiple times, for example, the <code>'connection'</code> event in <code>net.createServer()</code>, or just a single time like in <code>fs.open()</code>. A resource can also be closed before the callback is called. <code>AsyncHook</code> does not explicitly distinguish between these different cases but will represent them as the abstract concept that is a resource.</p> <p>If <a href="worker_threads.html#worker_threads_class_worker"><code>Worker</code></a>s are used, each thread has an independent <code>async_hooks</code> interface, and each thread will use a new set of async IDs.</p> <h2>Public API<span><a class="mark" href="#async_hooks_public_api" id="async_hooks_public_api">#</a></span></h2> <h3>Overview<span><a class="mark" href="#async_hooks_overview" id="async_hooks_overview">#</a></span></h3> <p>Following is a simple overview of the public API.</p> <pre><code class="language-js">const async_hooks = require('async_hooks'); // Return the ID of the current execution context. const eid = async_hooks.executionAsyncId(); // Return the ID of the handle responsible for triggering the callback of the // current execution scope to call. const tid = async_hooks.triggerAsyncId(); // Create a new AsyncHook instance. All of these callbacks are optional. const asyncHook = async_hooks.createHook({ init, before, after, destroy, promiseResolve }); // Allow callbacks of this AsyncHook instance to call. This is not an implicit // action after running the constructor, and must be explicitly run to begin // executing callbacks. asyncHook.enable(); // Disable listening for new asynchronous events. asyncHook.disable(); // // The following are the callbacks that can be passed to createHook(). // // init is called during object construction. The resource may not have // completed construction when this callback runs, therefore all fields of the // resource referenced by "asyncId" may not have been populated. function init(asyncId, type, triggerAsyncId, resource) { } // before is called just before the resource's callback is called. It can be // called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1 // time for requests (e.g. FSReqWrap). function before(asyncId) { } // after is called just after the resource's callback has finished. function after(asyncId) { } // destroy is called when an AsyncWrap instance is destroyed. function destroy(asyncId) { } // promiseResolve is called only for promise resources, when the // `resolve` function passed to the `Promise` constructor is invoked // (either directly or through other means of resolving a promise). function promiseResolve(asyncId) { } </code></pre> <h4>async_hooks.createHook(callbacks)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L121">[src]</a><span><a class="mark" href="#async_hooks_async_hooks_createhook_callbacks" id="async_hooks_async_hooks_createhook_callbacks">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.1.0</span> </div> <ul> <li> <p><code>callbacks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#async_hooks_hook_callbacks">Hook Callbacks</a> to register</p> <ul> <li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> callback</a>.</li> <li><code>before</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#async_hooks_before_asyncid"><code>before</code> callback</a>.</li> <li><code>after</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#async_hooks_after_asyncid"><code>after</code> callback</a>.</li> <li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#async_hooks_destroy_asyncid"><code>destroy</code> callback</a>.</li> </ul> </li> <li>Returns: <a href="async_hooks.html#async_hooks_async_hooks_createhook_callbacks" class="type"><AsyncHook></a> Instance used for disabling and enabling hooks</li> </ul> <p>Registers functions to be called for different lifetime events of each async operation.</p> <p>The callbacks <code>init()</code>/<code>before()</code>/<code>after()</code>/<code>destroy()</code> are called for the respective asynchronous event during a resource's lifetime.</p> <p>All callbacks are optional. For example, if only resource cleanup needs to be tracked, then only the <code>destroy</code> callback needs to be passed. The specifics of all functions that can be passed to <code>callbacks</code> is in the <a href="#async_hooks_hook_callbacks">Hook Callbacks</a> section.</p> <pre><code class="language-js">const async_hooks = require('async_hooks'); const asyncHook = async_hooks.createHook({ init(asyncId, type, triggerAsyncId, resource) { }, destroy(asyncId) { } }); </code></pre> <p>Note that the callbacks will be inherited via the prototype chain:</p> <pre><code class="language-js">class MyAsyncCallbacks { init(asyncId, type, triggerAsyncId, resource) { } destroy(asyncId) {} } class MyAddedCallbacks extends MyAsyncCallbacks { before(asyncId) { } after(asyncId) { } } const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); </code></pre> <h5>Error Handling<span><a class="mark" href="#async_hooks_error_handling" id="async_hooks_error_handling">#</a></span></h5> <p>If any <code>AsyncHook</code> callbacks throw, the application will print the stack trace and exit. The exit path does follow that of an uncaught exception, but all <code>'uncaughtException'</code> listeners are removed, thus forcing the process to exit. The <code>'exit'</code> callbacks will still be called unless the application is run with <code>--abort-on-uncaught-exception</code>, in which case a stack trace will be printed and the application exits, leaving a core file.</p> <p>The reason for this error handling behavior is that these callbacks are running at potentially volatile points in an object's lifetime, for example during class construction and destruction. Because of this, it is deemed necessary to bring down the process quickly in order to prevent an unintentional abort in the future. This is subject to change in the future if a comprehensive analysis is performed to ensure an exception can follow the normal control flow without unintentional side effects.</p> <h5>Printing in AsyncHooks callbacks<span><a class="mark" href="#async_hooks_printing_in_asynchooks_callbacks" id="async_hooks_printing_in_asynchooks_callbacks">#</a></span></h5> <p>Because printing to the console is an asynchronous operation, <code>console.log()</code> will cause the AsyncHooks callbacks to be called. Using <code>console.log()</code> or similar asynchronous operations inside an AsyncHooks callback function will thus cause an infinite recursion. An easy solution to this when debugging is to use a synchronous logging operation such as <code>fs.writeFileSync(file, msg, flag)</code>. This will print to the file and will not invoke AsyncHooks recursively because it is synchronous.</p> <pre><code class="language-js">const fs = require('fs'); const util = require('util'); function debug(...args) { // use a function like this one when debugging inside an AsyncHooks callback fs.writeFileSync('log.out', `${util.format(...args)}\n`, { flag: 'a' }); } </code></pre> <p>If an asynchronous operation is needed for logging, it is possible to keep track of what caused the asynchronous operation using the information provided by AsyncHooks itself. The logging should then be skipped when it was the logging itself that caused AsyncHooks callback to call. By doing this the otherwise infinite recursion is broken.</p> <h4>asyncHook.enable()<span><a class="mark" href="#async_hooks_asynchook_enable" id="async_hooks_asynchook_enable">#</a></span></h4> <ul> <li>Returns: <a href="async_hooks.html#async_hooks_async_hooks_createhook_callbacks" class="type"><AsyncHook></a> A reference to <code>asyncHook</code>.</li> </ul> <p>Enable the callbacks for a given <code>AsyncHook</code> instance. If no callbacks are provided enabling is a noop.</p> <p>The <code>AsyncHook</code> instance is disabled by default. If the <code>AsyncHook</code> instance should be enabled immediately after creation, the following pattern can be used.</p> <pre><code class="language-js">const async_hooks = require('async_hooks'); const hook = async_hooks.createHook(callbacks).enable(); </code></pre> <h4>asyncHook.disable()<span><a class="mark" href="#async_hooks_asynchook_disable" id="async_hooks_asynchook_disable">#</a></span></h4> <ul> <li>Returns: <a href="async_hooks.html#async_hooks_async_hooks_createhook_callbacks" class="type"><AsyncHook></a> A reference to <code>asyncHook</code>.</li> </ul> <p>Disable the callbacks for a given <code>AsyncHook</code> instance from the global pool of <code>AsyncHook</code> callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.</p> <p>For API consistency <code>disable()</code> also returns the <code>AsyncHook</code> instance.</p> <h4>Hook Callbacks<span><a class="mark" href="#async_hooks_hook_callbacks" id="async_hooks_hook_callbacks">#</a></span></h4> <p>Key events in the lifetime of asynchronous events have been categorized into four areas: instantiation, before/after the callback is called, and when the instance is destroyed.</p> <h5>init(asyncId, type, triggerAsyncId, resource)<span><a class="mark" href="#async_hooks_init_asyncid_type_triggerasyncid_resource" id="async_hooks_init_asyncid_type_triggerasyncid_resource">#</a></span></h5> <ul> <li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A unique ID for the async resource.</li> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of the async resource.</li> <li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The unique ID of the async resource in whose execution context this async resource was created.</li> <li><code>resource</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Reference to the resource representing the async operation, needs to be released during <em>destroy</em>.</li> </ul> <p>Called when a class is constructed that has the <em>possibility</em> to emit an asynchronous event. This <em>does not</em> mean the instance must call <code>before</code>/<code>after</code> before <code>destroy</code> is called, only that the possibility exists.</p> <p>This behavior can be observed by doing something like opening a resource then closing it before the resource can be used. The following snippet demonstrates this.</p> <pre><code class="language-js">require('net').createServer().listen(function() { this.close(); }); // OR clearTimeout(setTimeout(() => {}, 10)); </code></pre> <p>Every new resource is assigned an ID that is unique within the scope of the current Node.js instance.</p> <h6><code>type</code><span><a class="mark" href="#async_hooks_type" id="async_hooks_type">#</a></span></h6> <p>The <code>type</code> is a string identifying the type of resource that caused <code>init</code> to be called. Generally, it will correspond to the name of the resource's constructor.</p> <pre><code class="language-text">FSEVENTWRAP, FSREQWRAP, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPPARSER, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP, SHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP, TIMERWRAP, TTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST, RANDOMBYTESREQUEST, TLSWRAP, Timeout, Immediate, TickObject </code></pre> <p>There is also the <code>PROMISE</code> resource type, which is used to track <code>Promise</code> instances and asynchronous work scheduled by them.</p> <p>Users are able to define their own <code>type</code> when using the public embedder API.</p> <p>It is possible to have type name collisions. Embedders are encouraged to use unique prefixes, such as the npm package name, to prevent collisions when listening to the hooks.</p> <h6><code>triggerAsyncId</code><span><a class="mark" href="#async_hooks_triggerasyncid" id="async_hooks_triggerasyncid">#</a></span></h6> <p><code>triggerAsyncId</code> is the <code>asyncId</code> of the resource that caused (or "triggered") the new resource to initialize and that caused <code>init</code> to call. This is different from <code>async_hooks.executionAsyncId()</code> that only shows <em>when</em> a resource was created, while <code>triggerAsyncId</code> shows <em>why</em> a resource was created.</p> <p>The following is a simple demonstration of <code>triggerAsyncId</code>:</p> <pre><code class="language-js">async_hooks.createHook({ init(asyncId, type, triggerAsyncId) { const eid = async_hooks.executionAsyncId(); fs.writeSync( 1, `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`); } }).enable(); require('net').createServer((conn) => {}).listen(8080); </code></pre> <p>Output when hitting the server with <code>nc localhost 8080</code>:</p> <pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1 TCPWRAP(7): trigger: 5 execution: 0 </code></pre> <p>The <code>TCPSERVERWRAP</code> is the server which receives the connections.</p> <p>The <code>TCPWRAP</code> is the new connection from the client. When a new connection is made, the <code>TCPWrap</code> instance is immediately constructed. This happens outside of any JavaScript stack. (An <code>executionAsyncId()</code> of <code>0</code> means that it is being executed from C++ with no JavaScript stack above it.) With only that information, it would be impossible to link resources together in terms of what caused them to be created, so <code>triggerAsyncId</code> is given the task of propagating what resource is responsible for the new resource's existence.</p> <h6><code>resource</code><span><a class="mark" href="#async_hooks_resource" id="async_hooks_resource">#</a></span></h6> <p><code>resource</code> is an object that represents the actual async resource that has been initialized. This can contain useful information that can vary based on the value of <code>type</code>. For instance, for the <code>GETADDRINFOREQWRAP</code> resource type, <code>resource</code> provides the hostname used when looking up the IP address for the host in <code>net.Server.listen()</code>. The API for accessing this information is currently not considered public, but using the Embedder API, users can provide and document their own resource objects. For example, such a resource object could contain the SQL query being executed.</p> <p>In the case of Promises, the <code>resource</code> object will have <code>promise</code> property that refers to the <code>Promise</code> that is being initialized, and an <code>isChainedPromise</code> property, set to <code>true</code> if the promise has a parent promise, and <code>false</code> otherwise. For example, in the case of <code>b = a.then(handler)</code>, <code>a</code> is considered a parent <code>Promise</code> of <code>b</code>. Here, <code>b</code> is considered a chained promise.</p> <p>In some cases the resource object is reused for performance reasons, it is thus not safe to use it as a key in a <code>WeakMap</code> or add properties to it.</p> <h6>Asynchronous context example<span><a class="mark" href="#async_hooks_asynchronous_context_example" id="async_hooks_asynchronous_context_example">#</a></span></h6> <p>The following is an example with additional information about the calls to <code>init</code> between the <code>before</code> and <code>after</code> calls, specifically what the callback to <code>listen()</code> will look like. The output formatting is slightly more elaborate to make calling context easier to see.</p> <pre><code class="language-js">let indent = 0; async_hooks.createHook({ init(asyncId, type, triggerAsyncId) { const eid = async_hooks.executionAsyncId(); const indentStr = ' '.repeat(indent); fs.writeSync( 1, `${indentStr}${type}(${asyncId}):` + ` trigger: ${triggerAsyncId} execution: ${eid}\n`); }, before(asyncId) { const indentStr = ' '.repeat(indent); fs.writeFileSync('log.out', `${indentStr}before: ${asyncId}\n`, { flag: 'a' }); indent += 2; }, after(asyncId) { indent -= 2; const indentStr = ' '.repeat(indent); fs.writeFileSync('log.out', `${indentStr}after: ${asyncId}\n`, { flag: 'a' }); }, destroy(asyncId) { const indentStr = ' '.repeat(indent); fs.writeFileSync('log.out', `${indentStr}destroy: ${asyncId}\n`, { flag: 'a' }); }, }).enable(); require('net').createServer(() => {}).listen(8080, () => { // Let's wait 10ms before logging the server started. setTimeout(() => { console.log('>>>', async_hooks.executionAsyncId()); }, 10); }); </code></pre> <p>Output from only starting the server:</p> <pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1 TickObject(6): trigger: 5 execution: 1 before: 6 Timeout(7): trigger: 6 execution: 6 after: 6 destroy: 6 before: 7 >>> 7 TickObject(8): trigger: 7 execution: 7 after: 7 before: 8 after: 8 </code></pre> <p>As illustrated in the example, <code>executionAsyncId()</code> and <code>execution</code> each specify the value of the current execution context; which is delineated by calls to <code>before</code> and <code>after</code>.</p> <p>Only using <code>execution</code> to graph resource allocation results in the following:</p> <pre><code class="language-console">Timeout(7) -> TickObject(6) -> root(1) </code></pre> <p>The <code>TCPSERVERWRAP</code> is not part of this graph, even though it was the reason for <code>console.log()</code> being called. This is because binding to a port without a hostname is a <em>synchronous</em> operation, but to maintain a completely asynchronous API the user's callback is placed in a <code>process.nextTick()</code>.</p> <p>The graph only shows <em>when</em> a resource was created, not <em>why</em>, so to track the <em>why</em> use <code>triggerAsyncId</code>.</p> <h5>before(asyncId)<span><a class="mark" href="#async_hooks_before_asyncid" id="async_hooks_before_asyncid">#</a></span></h5> <ul> <li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>When an asynchronous operation is initiated (such as a TCP server receiving a new connection) or completes (such as writing data to disk) a callback is called to notify the user. The <code>before</code> callback is called just before said callback is executed. <code>asyncId</code> is the unique identifier assigned to the resource about to execute the callback.</p> <p>The <code>before</code> callback will be called 0 to N times. The <code>before</code> callback will typically be called 0 times if the asynchronous operation was cancelled or, for example, if no connections are received by a TCP server. Persistent asynchronous resources like a TCP server will typically call the <code>before</code> callback multiple times, while other operations like <code>fs.open()</code> will call it only once.</p> <h5>after(asyncId)<span><a class="mark" href="#async_hooks_after_asyncid" id="async_hooks_after_asyncid">#</a></span></h5> <ul> <li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Called immediately after the callback specified in <code>before</code> is completed.</p> <p>If an uncaught exception occurs during execution of the callback, then <code>after</code> will run <em>after</em> the <code>'uncaughtException'</code> event is emitted or a <code>domain</code>'s handler runs.</p> <h5>destroy(asyncId)<span><a class="mark" href="#async_hooks_destroy_asyncid" id="async_hooks_destroy_asyncid">#</a></span></h5> <ul> <li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Called after the resource corresponding to <code>asyncId</code> is destroyed. It is also called asynchronously from the embedder API <code>emitDestroy()</code>.</p> <p>Some resources depend on garbage collection for cleanup, so if a reference is made to the <code>resource</code> object passed to <code>init</code> it is possible that <code>destroy</code> will never be called, causing a memory leak in the application. If the resource does not depend on garbage collection, then this will not be an issue.</p> <h5>promiseResolve(asyncId)<span><a class="mark" href="#async_hooks_promiseresolve_asyncid" id="async_hooks_promiseresolve_asyncid">#</a></span></h5> <ul> <li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Called when the <code>resolve</code> function passed to the <code>Promise</code> constructor is invoked (either directly or through other means of resolving a promise).</p> <p>Note that <code>resolve()</code> does not do any observable synchronous work.</p> <p>The <code>Promise</code> is not necessarily fulfilled or rejected at this point if the <code>Promise</code> was resolved by assuming the state of another <code>Promise</code>.</p> <pre><code class="language-js">new Promise((resolve) => resolve(true)).then((a) => {}); </code></pre> <p>calls the following callbacks:</p> <pre><code class="language-text">init for PROMISE with id 5, trigger id: 1 promise resolve 5 # corresponds to resolve(true) init for PROMISE with id 6, trigger id: 5 # the Promise returned by then() before 6 # the then() callback is entered promise resolve 6 # the then() callback resolves the promise by returning after 6 </code></pre> <h4>async_hooks.executionAsyncId()<span><a class="mark" href="#async_hooks_async_hooks_executionasyncid" id="async_hooks_async_hooks_executionasyncid">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.2.0</td> <td><p>Renamed from <code>currentId</code></p></td></tr> <tr><td>v8.1.0</td> <td><p><span>Added in: v8.1.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The <code>asyncId</code> of the current execution context. Useful to track when something calls.</li> </ul> <pre><code class="language-js">const async_hooks = require('async_hooks'); console.log(async_hooks.executionAsyncId()); // 1 - bootstrap fs.open(path, 'r', (err, fd) => { console.log(async_hooks.executionAsyncId()); // 6 - open() }); </code></pre> <p>The ID returned from <code>executionAsyncId()</code> is related to execution timing, not causality (which is covered by <code>triggerAsyncId()</code>):</p> <pre><code class="language-js">const server = net.createServer((conn) => { // Returns the ID of the server, not of the new connection, because the // callback runs in the execution scope of the server's MakeCallback(). async_hooks.executionAsyncId(); }).listen(port, () => { // Returns the ID of a TickObject (i.e. process.nextTick()) because all // callbacks passed to .listen() are wrapped in a nextTick(). async_hooks.executionAsyncId(); }); </code></pre> <p>Note that promise contexts may not get precise <code>executionAsyncIds</code> by default. See the section on <a href="#async_hooks_promise_execution_tracking">promise execution tracking</a>.</p> <h4>async_hooks.triggerAsyncId()<span><a class="mark" href="#async_hooks_async_hooks_triggerasyncid" id="async_hooks_async_hooks_triggerasyncid">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the resource responsible for calling the callback that is currently being executed.</li> </ul> <pre><code class="language-js">const server = net.createServer((conn) => { // The resource that caused (or triggered) this callback to be called // was that of the new connection. Thus the return value of triggerAsyncId() // is the asyncId of "conn". async_hooks.triggerAsyncId(); }).listen(port, () => { // Even though all callbacks passed to .listen() are wrapped in a nextTick() // the callback itself exists because the call to the server's .listen() // was made. So the return value would be the ID of the server. async_hooks.triggerAsyncId(); }); </code></pre> <p>Note that promise contexts may not get valid <code>triggerAsyncId</code>s by default. See the section on <a href="#async_hooks_promise_execution_tracking">promise execution tracking</a>.</p> <h2>Promise execution tracking<span><a class="mark" href="#async_hooks_promise_execution_tracking" id="async_hooks_promise_execution_tracking">#</a></span></h2> <p>By default, promise executions are not assigned <code>asyncId</code>s due to the relatively expensive nature of the <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">promise introspection API</a> provided by V8. This means that programs using promises or <code>async</code>/<code>await</code> will not get correct execution and trigger ids for promise callback contexts by default.</p> <pre><code class="language-js">const ah = require('async_hooks'); Promise.resolve(1729).then(() => { console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`); }); // produces: // eid 1 tid 0 </code></pre> <p>Observe that the <code>then()</code> callback claims to have executed in the context of the outer scope even though there was an asynchronous hop involved. Also note that the <code>triggerAsyncId</code> value is <code>0</code>, which means that we are missing context about the resource that caused (triggered) the <code>then()</code> callback to be executed.</p> <p>Installing async hooks via <code>async_hooks.createHook</code> enables promise execution tracking:</p> <pre><code class="language-js">const ah = require('async_hooks'); ah.createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled. Promise.resolve(1729).then(() => { console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`); }); // produces: // eid 7 tid 6 </code></pre> <p>In this example, adding any actual hook function enabled the tracking of promises. There are two promises in the example above; the promise created by <code>Promise.resolve()</code> and the promise returned by the call to <code>then()</code>. In the example above, the first promise got the <code>asyncId</code> <code>6</code> and the latter got <code>asyncId</code> <code>7</code>. During the execution of the <code>then()</code> callback, we are executing in the context of promise with <code>asyncId</code> <code>7</code>. This promise was triggered by async resource <code>6</code>.</p> <p>Another subtlety with promises is that <code>before</code> and <code>after</code> callbacks are run only on chained promises. That means promises not created by <code>then()</code>/<code>catch()</code> will not have the <code>before</code> and <code>after</code> callbacks fired on them. For more details see the details of the V8 <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">PromiseHooks</a> API.</p> <h2>JavaScript Embedder API<span><a class="mark" href="#async_hooks_javascript_embedder_api" id="async_hooks_javascript_embedder_api">#</a></span></h2> <p>Library developers that handle their own asynchronous resources performing tasks like I/O, connection pooling, or managing callback queues may use the <code>AsyncWrap</code> JavaScript API so that all the appropriate callbacks are called.</p> <h3>Class: AsyncResource<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L141">[src]</a><span><a class="mark" href="#async_hooks_class_asyncresource" id="async_hooks_class_asyncresource">#</a></span></h3> <p>The class <code>AsyncResource</code> is designed to be extended by the embedder's async resources. Using this, users can easily trigger the lifetime events of their own resources.</p> <p>The <code>init</code> hook will trigger when an <code>AsyncResource</code> is instantiated.</p> <p>The following is an overview of the <code>AsyncResource</code> API.</p> <pre><code class="language-js">const { AsyncResource, executionAsyncId } = require('async_hooks'); // AsyncResource() is meant to be extended. Instantiating a // new AsyncResource() also triggers init. If triggerAsyncId is omitted then // async_hook.executionAsyncId() is used. const asyncResource = new AsyncResource( type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false } ); // Run a function in the execution context of the resource. This will // * establish the context of the resource // * trigger the AsyncHooks before callbacks // * call the provided function `fn` with the supplied arguments // * trigger the AsyncHooks after callbacks // * restore the original execution context asyncResource.runInAsyncScope(fn, thisArg, ...args); // Call AsyncHooks destroy callbacks. asyncResource.emitDestroy(); // Return the unique ID assigned to the AsyncResource instance. asyncResource.asyncId(); // Return the trigger ID for the AsyncResource instance. asyncResource.triggerAsyncId(); </code></pre> <h4>new AsyncResource(type[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L142">[src]</a><span><a class="mark" href="#async_hooks_new_asyncresource_type_options" id="async_hooks_new_asyncresource_type_options">#</a></span></h4> <ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of async event.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the execution context that created this async event. <strong>Default:</strong> <code>executionAsyncId()</code>.</li> <li><code>requireManualDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Disables automatic <code>emitDestroy</code> when the object is garbage collected. This usually does not need to be set (even if <code>emitDestroy</code> is called manually), unless the resource's <code>asyncId</code> is retrieved and the sensitive API's <code>emitDestroy</code> is called with it. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> </ul> <p>Example usage:</p> <pre><code class="language-js">class DBQuery extends AsyncResource { constructor(db) { super('DBQuery'); this.db = db; } getInfo(query, callback) { this.db.get(query, (err, data) => { this.runInAsyncScope(callback, null, err, data); }); } close() { this.db = null; this.emitDestroy(); } } </code></pre> <h4>asyncResource.runInAsyncScope(fn[, thisArg, ...args])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L184">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args" id="async_hooks_asyncresource_runinasyncscope_fn_thisarg_args">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.6.0</span> </div> <ul> <li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to call in the execution context of this async resource.</li> <li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The receiver to be used for the function call.</li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass to the function.</li> </ul> <p>Call the provided function with the provided arguments in the execution context of the async resource. This will establish the context, trigger the AsyncHooks before callbacks, call the function, trigger the AsyncHooks after callbacks, and then restore the original execution context.</p> <h4>asyncResource.emitBefore()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L172">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_emitbefore" id="async_hooks_asyncresource_emitbefore">#</a></span></h4> <div class="api_metadata"> <span>Deprecated since: v9.6.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope()</code></a> instead.</div><p></p> <p>Call all <code>before</code> callbacks to notify that a new asynchronous execution context is being entered. If nested calls to <code>emitBefore()</code> are made, the stack of <code>asyncId</code>s will be tracked and properly unwound.</p> <p><code>before</code> and <code>after</code> calls must be unwound in the same order that they are called. Otherwise, an unrecoverable exception will occur and the process will abort. For this reason, the <code>emitBefore</code> and <code>emitAfter</code> APIs are considered deprecated. Please use <code>runInAsyncScope</code>, as it provides a much safer alternative.</p> <h4>asyncResource.emitAfter()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L178">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_emitafter" id="async_hooks_asyncresource_emitafter">#</a></span></h4> <div class="api_metadata"> <span>Deprecated since: v9.6.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope()</code></a> instead.</div><p></p> <p>Call all <code>after</code> callbacks. If nested calls to <code>emitBefore()</code> were made, then make sure the stack is unwound properly. Otherwise an error will be thrown.</p> <p>If the user's callback throws an exception, <code>emitAfter()</code> will automatically be called for all <code>asyncId</code>s on the stack if the error is handled by a domain or <code>'uncaughtException'</code> handler.</p> <p><code>before</code> and <code>after</code> calls must be unwound in the same order that they are called. Otherwise, an unrecoverable exception will occur and the process will abort. For this reason, the <code>emitBefore</code> and <code>emitAfter</code> APIs are considered deprecated. Please use <code>runInAsyncScope</code>, as it provides a much safer alternative.</p> <h4>asyncResource.emitDestroy()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L195">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_emitdestroy" id="async_hooks_asyncresource_emitdestroy">#</a></span></h4> <ul> <li>Returns: <a href="async_hooks.html#async_hooks_class_asyncresource" class="type"><AsyncResource></a> A reference to <code>asyncResource</code>.</li> </ul> <p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will be thrown if it is called more than once. This <strong>must</strong> be manually called. If the resource is left to be collected by the GC then the <code>destroy</code> hooks will never be called.</p> <h4>asyncResource.asyncId()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L201">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_asyncid" id="async_hooks_asyncresource_asyncid">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The unique <code>asyncId</code> assigned to the resource.</li> </ul> <h4>asyncResource.triggerAsyncId()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L205">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_triggerasyncid" id="async_hooks_asyncresource_triggerasyncid">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The same <code>triggerAsyncId</code> that is passed to the <code>AsyncResource</code> constructor.</li> </ul> </div> </div> </div> <script src="assets/sh_main.js"></script> <script src="assets/sh_javascript.min.js"></script> <script>highlight(undefined, undefined, 'pre');</script> </body> </html>