xref: /third_party/node/doc/api/async_hooks.html (revision 1cb0ef41)
1<!DOCTYPE html>
2<html lang="en">
3<head>
4  <meta charset="utf-8">
5  <meta name="viewport" content="width=device-width">
6  <meta name="nodejs.org:node-version" content="v18.20.1">
7  <title>Async hooks | Node.js v18.20.1 Documentation</title>
8  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
9  <link rel="stylesheet" href="assets/style.css">
10  <link rel="stylesheet" href="assets/hljs.css">
11  <link rel="canonical" href="https://nodejs.org/api/async_hooks.html">
12  <script async defer src="assets/api.js" type="text/javascript"></script>
13  <style>@media(max-width:606px){.with-48-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:542px){.with-40-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:1072px){.with-72-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:1048px){.with-69-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:1144px){.with-81-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:590px){.with-46-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:638px){.with-52-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:1080px){.with-73-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:1176px){.with-85-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}</style>
14</head>
15<body class="alt apidoc" id="api-section-async_hooks">
16  <div id="content" class="clearfix">
17    <div id="column2" class="interior">
18      <div id="intro" class="interior">
19        <a href="/" title="Go back to the home page">
20          Node.js
21        </a>
22      </div>
23      <ul>
24<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
25<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
26</ul>
27<hr class="line">
28<ul>
29<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
30<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
31<li><a href="async_hooks.html" class="nav-async_hooks active">Async hooks</a></li>
32<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
33<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
34<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
35<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
36<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
37<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
38<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
39<li><a href="console.html" class="nav-console">Console</a></li>
40<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
41<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
42<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
43<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
44<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
45<li><a href="dns.html" class="nav-dns">DNS</a></li>
46<li><a href="domain.html" class="nav-domain">Domain</a></li>
47<li><a href="errors.html" class="nav-errors">Errors</a></li>
48<li><a href="events.html" class="nav-events">Events</a></li>
49<li><a href="fs.html" class="nav-fs">File system</a></li>
50<li><a href="globals.html" class="nav-globals">Globals</a></li>
51<li><a href="http.html" class="nav-http">HTTP</a></li>
52<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
53<li><a href="https.html" class="nav-https">HTTPS</a></li>
54<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
55<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
56<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
57<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
58<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
59<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
60<li><a href="net.html" class="nav-net">Net</a></li>
61<li><a href="os.html" class="nav-os">OS</a></li>
62<li><a href="path.html" class="nav-path">Path</a></li>
63<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
64<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
65<li><a href="process.html" class="nav-process">Process</a></li>
66<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
67<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
68<li><a href="readline.html" class="nav-readline">Readline</a></li>
69<li><a href="repl.html" class="nav-repl">REPL</a></li>
70<li><a href="report.html" class="nav-report">Report</a></li>
71<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
72<li><a href="stream.html" class="nav-stream">Stream</a></li>
73<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
74<li><a href="test.html" class="nav-test">Test runner</a></li>
75<li><a href="timers.html" class="nav-timers">Timers</a></li>
76<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
77<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
78<li><a href="tty.html" class="nav-tty">TTY</a></li>
79<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
80<li><a href="url.html" class="nav-url">URL</a></li>
81<li><a href="util.html" class="nav-util">Utilities</a></li>
82<li><a href="v8.html" class="nav-v8">V8</a></li>
83<li><a href="vm.html" class="nav-vm">VM</a></li>
84<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
85<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
86<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
87<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
88<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
89</ul>
90<hr class="line">
91<ul>
92<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
93</ul>
94    </div>
95
96    <div id="column1" data-id="async_hooks" class="interior">
97      <header class="header">
98        <div class="header-container">
99          <h1>Node.js v18.20.1 documentation</h1>
100          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
101            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
102              <path fill="none" d="M0 0h24v24H0z" />
103              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
104              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
105            </svg>
106            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
107              <path d="M0 0h24v24H0z" fill="none" />
108              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
109            </svg>
110          </button>
111        </div>
112        <div id="gtoc">
113          <ul>
114            <li class="pinned-header">Node.js v18.20.1</li>
115            
116    <li class="picker-header">
117      <a href="#">
118        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
119        Table of contents
120      </a>
121
122      <div class="picker"><div class="toc"><ul>
123<li><span class="stability_1"><a href="#async-hooks">Async hooks</a></span>
124<ul>
125<li><a href="#terminology">Terminology</a></li>
126<li><a href="#overview">Overview</a></li>
127<li><a href="#async_hookscreatehookcallbacks"><code>async_hooks.createHook(callbacks)</code></a>
128<ul>
129<li><a href="#error-handling">Error handling</a></li>
130<li><a href="#printing-in-asynchook-callbacks">Printing in <code>AsyncHook</code> callbacks</a></li>
131</ul>
132</li>
133<li><a href="#class-asynchook">Class: <code>AsyncHook</code></a>
134<ul>
135<li><a href="#asynchookenable"><code>asyncHook.enable()</code></a></li>
136<li><a href="#asynchookdisable"><code>asyncHook.disable()</code></a></li>
137<li><a href="#hook-callbacks">Hook callbacks</a>
138<ul>
139<li><a href="#initasyncid-type-triggerasyncid-resource"><code>init(asyncId, type, triggerAsyncId, resource)</code></a>
140<ul>
141<li><a href="#type"><code>type</code></a></li>
142<li><a href="#triggerasyncid"><code>triggerAsyncId</code></a></li>
143<li><a href="#resource"><code>resource</code></a></li>
144<li><a href="#asynchronous-context-example">Asynchronous context example</a></li>
145</ul>
146</li>
147<li><a href="#beforeasyncid"><code>before(asyncId)</code></a></li>
148<li><a href="#afterasyncid"><code>after(asyncId)</code></a></li>
149<li><a href="#destroyasyncid"><code>destroy(asyncId)</code></a></li>
150<li><a href="#promiseresolveasyncid"><code>promiseResolve(asyncId)</code></a></li>
151</ul>
152</li>
153<li><a href="#async_hooksexecutionasyncresource"><code>async_hooks.executionAsyncResource()</code></a></li>
154<li><a href="#async_hooksexecutionasyncid"><code>async_hooks.executionAsyncId()</code></a></li>
155<li><a href="#async_hookstriggerasyncid"><code>async_hooks.triggerAsyncId()</code></a></li>
156<li><a href="#async_hooksasyncwrapproviders"><code>async_hooks.asyncWrapProviders</code></a></li>
157</ul>
158</li>
159<li><a href="#promise-execution-tracking">Promise execution tracking</a></li>
160<li><a href="#javascript-embedder-api">JavaScript embedder API</a>
161<ul>
162<li><a href="#class-asyncresource">Class: <code>AsyncResource</code></a></li>
163</ul>
164</li>
165<li><a href="#class-asynclocalstorage">Class: <code>AsyncLocalStorage</code></a></li>
166</ul>
167</li>
168</ul></div></div>
169    </li>
170  
171            
172    <li class="picker-header">
173      <a href="#">
174        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
175        Index
176      </a>
177
178      <div class="picker"><ul>
179<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
180<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
181
182      <li>
183        <a href="index.html">Index</a>
184      </li>
185    </ul>
186  
187<hr class="line">
188<ul>
189<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
190<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
191<li><a href="async_hooks.html" class="nav-async_hooks active">Async hooks</a></li>
192<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
193<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
194<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
195<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
196<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
197<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
198<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
199<li><a href="console.html" class="nav-console">Console</a></li>
200<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
201<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
202<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
203<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
204<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
205<li><a href="dns.html" class="nav-dns">DNS</a></li>
206<li><a href="domain.html" class="nav-domain">Domain</a></li>
207<li><a href="errors.html" class="nav-errors">Errors</a></li>
208<li><a href="events.html" class="nav-events">Events</a></li>
209<li><a href="fs.html" class="nav-fs">File system</a></li>
210<li><a href="globals.html" class="nav-globals">Globals</a></li>
211<li><a href="http.html" class="nav-http">HTTP</a></li>
212<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
213<li><a href="https.html" class="nav-https">HTTPS</a></li>
214<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
215<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
216<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
217<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
218<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
219<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
220<li><a href="net.html" class="nav-net">Net</a></li>
221<li><a href="os.html" class="nav-os">OS</a></li>
222<li><a href="path.html" class="nav-path">Path</a></li>
223<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
224<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
225<li><a href="process.html" class="nav-process">Process</a></li>
226<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
227<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
228<li><a href="readline.html" class="nav-readline">Readline</a></li>
229<li><a href="repl.html" class="nav-repl">REPL</a></li>
230<li><a href="report.html" class="nav-report">Report</a></li>
231<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
232<li><a href="stream.html" class="nav-stream">Stream</a></li>
233<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
234<li><a href="test.html" class="nav-test">Test runner</a></li>
235<li><a href="timers.html" class="nav-timers">Timers</a></li>
236<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
237<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
238<li><a href="tty.html" class="nav-tty">TTY</a></li>
239<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
240<li><a href="url.html" class="nav-url">URL</a></li>
241<li><a href="util.html" class="nav-util">Utilities</a></li>
242<li><a href="v8.html" class="nav-v8">V8</a></li>
243<li><a href="vm.html" class="nav-vm">VM</a></li>
244<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
245<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
246<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
247<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
248<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
249</ul>
250<hr class="line">
251<ul>
252<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
253</ul></div>
254    </li>
255  
256            
257    <li class="picker-header">
258      <a href="#">
259        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
260        Other versions
261      </a>
262      <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v21.x/api/async_hooks.html">21.x</a></li>
263<li><a href="https://nodejs.org/docs/latest-v20.x/api/async_hooks.html">20.x <b>LTS</b></a></li>
264<li><a href="https://nodejs.org/docs/latest-v19.x/api/async_hooks.html">19.x</a></li>
265<li><a href="https://nodejs.org/docs/latest-v18.x/api/async_hooks.html">18.x <b>LTS</b></a></li>
266<li><a href="https://nodejs.org/docs/latest-v17.x/api/async_hooks.html">17.x</a></li>
267<li><a href="https://nodejs.org/docs/latest-v16.x/api/async_hooks.html">16.x</a></li>
268<li><a href="https://nodejs.org/docs/latest-v15.x/api/async_hooks.html">15.x</a></li>
269<li><a href="https://nodejs.org/docs/latest-v14.x/api/async_hooks.html">14.x</a></li>
270<li><a href="https://nodejs.org/docs/latest-v13.x/api/async_hooks.html">13.x</a></li>
271<li><a href="https://nodejs.org/docs/latest-v12.x/api/async_hooks.html">12.x</a></li>
272<li><a href="https://nodejs.org/docs/latest-v11.x/api/async_hooks.html">11.x</a></li>
273<li><a href="https://nodejs.org/docs/latest-v10.x/api/async_hooks.html">10.x</a></li>
274<li><a href="https://nodejs.org/docs/latest-v9.x/api/async_hooks.html">9.x</a></li>
275<li><a href="https://nodejs.org/docs/latest-v8.x/api/async_hooks.html">8.x</a></li></ol></div>
276    </li>
277  
278            <li class="picker-header">
279              <a href="#">
280                <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
281                Options
282              </a>
283        
284              <div class="picker">
285                <ul>
286                  <li>
287                    <a href="all.html">View on single page</a>
288                  </li>
289                  <li>
290                    <a href="async_hooks.json">View as JSON</a>
291                  </li>
292                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/async_hooks.md">Edit on GitHub</a></li>    
293                </ul>
294              </div>
295            </li>
296          </ul>
297        </div>
298        <hr>
299      </header>
300
301      <details id="toc" open><summary>Table of contents</summary><ul>
302<li><span class="stability_1"><a href="#async-hooks">Async hooks</a></span>
303<ul>
304<li><a href="#terminology">Terminology</a></li>
305<li><a href="#overview">Overview</a></li>
306<li><a href="#async_hookscreatehookcallbacks"><code>async_hooks.createHook(callbacks)</code></a>
307<ul>
308<li><a href="#error-handling">Error handling</a></li>
309<li><a href="#printing-in-asynchook-callbacks">Printing in <code>AsyncHook</code> callbacks</a></li>
310</ul>
311</li>
312<li><a href="#class-asynchook">Class: <code>AsyncHook</code></a>
313<ul>
314<li><a href="#asynchookenable"><code>asyncHook.enable()</code></a></li>
315<li><a href="#asynchookdisable"><code>asyncHook.disable()</code></a></li>
316<li><a href="#hook-callbacks">Hook callbacks</a>
317<ul>
318<li><a href="#initasyncid-type-triggerasyncid-resource"><code>init(asyncId, type, triggerAsyncId, resource)</code></a>
319<ul>
320<li><a href="#type"><code>type</code></a></li>
321<li><a href="#triggerasyncid"><code>triggerAsyncId</code></a></li>
322<li><a href="#resource"><code>resource</code></a></li>
323<li><a href="#asynchronous-context-example">Asynchronous context example</a></li>
324</ul>
325</li>
326<li><a href="#beforeasyncid"><code>before(asyncId)</code></a></li>
327<li><a href="#afterasyncid"><code>after(asyncId)</code></a></li>
328<li><a href="#destroyasyncid"><code>destroy(asyncId)</code></a></li>
329<li><a href="#promiseresolveasyncid"><code>promiseResolve(asyncId)</code></a></li>
330</ul>
331</li>
332<li><a href="#async_hooksexecutionasyncresource"><code>async_hooks.executionAsyncResource()</code></a></li>
333<li><a href="#async_hooksexecutionasyncid"><code>async_hooks.executionAsyncId()</code></a></li>
334<li><a href="#async_hookstriggerasyncid"><code>async_hooks.triggerAsyncId()</code></a></li>
335<li><a href="#async_hooksasyncwrapproviders"><code>async_hooks.asyncWrapProviders</code></a></li>
336</ul>
337</li>
338<li><a href="#promise-execution-tracking">Promise execution tracking</a></li>
339<li><a href="#javascript-embedder-api">JavaScript embedder API</a>
340<ul>
341<li><a href="#class-asyncresource">Class: <code>AsyncResource</code></a></li>
342</ul>
343</li>
344<li><a href="#class-asynclocalstorage">Class: <code>AsyncLocalStorage</code></a></li>
345</ul>
346</li>
347</ul></details>
348
349      <div id="apicontent">
350        <h2>Async hooks<span><a class="mark" href="#async-hooks" id="async-hooks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks"></a></h2>
351
352<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental. Please migrate away from this API, if you can.
353We do not recommend using the <a href="#async_hookscreatehookcallbacks"><code>createHook</code></a>, <a href="#class-asynchook"><code>AsyncHook</code></a>, and
354<a href="#async_hooksexecutionasyncresource"><code>executionAsyncResource</code></a> APIs as they have usability issues, safety risks,
355and performance implications. Async context tracking use cases are better
356served by the stable <a href="async_context.html#class-asynclocalstorage"><code>AsyncLocalStorage</code></a> API. If you have a use case for
357<code>createHook</code>, <code>AsyncHook</code>, or <code>executionAsyncResource</code> beyond the context
358tracking need solved by <a href="async_context.html#class-asynclocalstorage"><code>AsyncLocalStorage</code></a> or diagnostics data currently
359provided by <a href="diagnostics_channel.html">Diagnostics Channel</a>, please open an issue at
360<a href="https://github.com/nodejs/node/issues">https://github.com/nodejs/node/issues</a> describing your use case so we can
361create a more purpose-focused API.</div><p></p>
362<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>
363<p>We strongly discourage the use of the <code>async_hooks</code> API.
364Other APIs that can cover most of its use cases include:</p>
365<ul>
366<li><a href="async_context.html#class-asynclocalstorage"><code>AsyncLocalStorage</code></a> tracks async context</li>
367<li><a href="process.html#processgetactiveresourcesinfo"><code>process.getActiveResourcesInfo()</code></a> tracks active resources</li>
368</ul>
369<p>The <code>node:async_hooks</code> module provides an API to track asynchronous resources.
370It can be accessed using:</p>
371
372<pre class="with-48-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> async_hooks <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);</code><button class="copy-button">copy</button></pre>
373<section><h3>Terminology<span><a class="mark" href="#terminology" id="terminology">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_terminology"></a></h3>
374<p>An asynchronous resource represents an object with an associated callback.
375This callback may be called multiple times, such as the <code>'connection'</code>
376event in <code>net.createServer()</code>, or just a single time like in <code>fs.open()</code>.
377A resource can also be closed before the callback is called. <code>AsyncHook</code> does
378not explicitly distinguish between these different cases but will represent them
379as the abstract concept that is a resource.</p>
380<p>If <a href="worker_threads.html#class-worker"><code>Worker</code></a>s are used, each thread has an independent <code>async_hooks</code>
381interface, and each thread will use a new set of async IDs.</p>
382</section><section><h3>Overview<span><a class="mark" href="#overview" id="overview">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_overview"></a></h3>
383<p>Following is a simple overview of the public API.</p>
384
385<pre class="with-48-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> async_hooks <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
386
387<span class="hljs-comment">// Return the ID of the current execution context.</span>
388<span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
389
390<span class="hljs-comment">// Return the ID of the handle responsible for triggering the callback of the</span>
391<span class="hljs-comment">// current execution scope to call.</span>
392<span class="hljs-keyword">const</span> tid = async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
393
394<span class="hljs-comment">// Create a new AsyncHook instance. All of these callbacks are optional.</span>
395<span class="hljs-keyword">const</span> asyncHook =
396    async_hooks.<span class="hljs-title function_">createHook</span>({ init, before, after, destroy, promiseResolve });
397
398<span class="hljs-comment">// Allow callbacks of this AsyncHook instance to call. This is not an implicit</span>
399<span class="hljs-comment">// action after running the constructor, and must be explicitly run to begin</span>
400<span class="hljs-comment">// executing callbacks.</span>
401asyncHook.<span class="hljs-title function_">enable</span>();
402
403<span class="hljs-comment">// Disable listening for new asynchronous events.</span>
404asyncHook.<span class="hljs-title function_">disable</span>();
405
406<span class="hljs-comment">//</span>
407<span class="hljs-comment">// The following are the callbacks that can be passed to createHook().</span>
408<span class="hljs-comment">//</span>
409
410<span class="hljs-comment">// init() is called during object construction. The resource may not have</span>
411<span class="hljs-comment">// completed construction when this callback runs. Therefore, all fields of the</span>
412<span class="hljs-comment">// resource referenced by "asyncId" may not have been populated.</span>
413<span class="hljs-keyword">function</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { }
414
415<span class="hljs-comment">// before() is called just before the resource's callback is called. It can be</span>
416<span class="hljs-comment">// called 0-N times for handles (such as TCPWrap), and will be called exactly 1</span>
417<span class="hljs-comment">// time for requests (such as FSReqCallback).</span>
418<span class="hljs-keyword">function</span> <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }
419
420<span class="hljs-comment">// after() is called just after the resource's callback has finished.</span>
421<span class="hljs-keyword">function</span> <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }
422
423<span class="hljs-comment">// destroy() is called when the resource is destroyed.</span>
424<span class="hljs-keyword">function</span> <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { }
425
426<span class="hljs-comment">// promiseResolve() is called only for promise resources, when the</span>
427<span class="hljs-comment">// resolve() function passed to the Promise constructor is invoked</span>
428<span class="hljs-comment">// (either directly or through other means of resolving a promise).</span>
429<span class="hljs-keyword">function</span> <span class="hljs-title function_">promiseResolve</span>(<span class="hljs-params">asyncId</span>) { }</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
430
431<span class="hljs-comment">// Return the ID of the current execution context.</span>
432<span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
433
434<span class="hljs-comment">// Return the ID of the handle responsible for triggering the callback of the</span>
435<span class="hljs-comment">// current execution scope to call.</span>
436<span class="hljs-keyword">const</span> tid = async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
437
438<span class="hljs-comment">// Create a new AsyncHook instance. All of these callbacks are optional.</span>
439<span class="hljs-keyword">const</span> asyncHook =
440    async_hooks.<span class="hljs-title function_">createHook</span>({ init, before, after, destroy, promiseResolve });
441
442<span class="hljs-comment">// Allow callbacks of this AsyncHook instance to call. This is not an implicit</span>
443<span class="hljs-comment">// action after running the constructor, and must be explicitly run to begin</span>
444<span class="hljs-comment">// executing callbacks.</span>
445asyncHook.<span class="hljs-title function_">enable</span>();
446
447<span class="hljs-comment">// Disable listening for new asynchronous events.</span>
448asyncHook.<span class="hljs-title function_">disable</span>();
449
450<span class="hljs-comment">//</span>
451<span class="hljs-comment">// The following are the callbacks that can be passed to createHook().</span>
452<span class="hljs-comment">//</span>
453
454<span class="hljs-comment">// init() is called during object construction. The resource may not have</span>
455<span class="hljs-comment">// completed construction when this callback runs. Therefore, all fields of the</span>
456<span class="hljs-comment">// resource referenced by "asyncId" may not have been populated.</span>
457<span class="hljs-keyword">function</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { }
458
459<span class="hljs-comment">// before() is called just before the resource's callback is called. It can be</span>
460<span class="hljs-comment">// called 0-N times for handles (such as TCPWrap), and will be called exactly 1</span>
461<span class="hljs-comment">// time for requests (such as FSReqCallback).</span>
462<span class="hljs-keyword">function</span> <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }
463
464<span class="hljs-comment">// after() is called just after the resource's callback has finished.</span>
465<span class="hljs-keyword">function</span> <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }
466
467<span class="hljs-comment">// destroy() is called when the resource is destroyed.</span>
468<span class="hljs-keyword">function</span> <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { }
469
470<span class="hljs-comment">// promiseResolve() is called only for promise resources, when the</span>
471<span class="hljs-comment">// resolve() function passed to the Promise constructor is invoked</span>
472<span class="hljs-comment">// (either directly or through other means of resolving a promise).</span>
473<span class="hljs-keyword">function</span> <span class="hljs-title function_">promiseResolve</span>(<span class="hljs-params">asyncId</span>) { }</code><button class="copy-button">copy</button></pre>
474</section><section><h3><code>async_hooks.createHook(callbacks)</code><span><a class="mark" href="#async_hookscreatehookcallbacks" id="async_hookscreatehookcallbacks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_createhook_callbacks"></a></h3>
475<div class="api_metadata">
476<span>Added in: v8.1.0</span>
477</div>
478<ul>
479<li><code>callbacks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#hook-callbacks">Hook Callbacks</a> to register
480<ul>
481<li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#initasyncid-type-triggerasyncid-resource"><code>init</code> callback</a>.</li>
482<li><code>before</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#beforeasyncid"><code>before</code> callback</a>.</li>
483<li><code>after</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#afterasyncid"><code>after</code> callback</a>.</li>
484<li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#destroyasyncid"><code>destroy</code> callback</a>.</li>
485<li><code>promiseResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#promiseresolveasyncid"><code>promiseResolve</code> callback</a>.</li>
486</ul>
487</li>
488<li>Returns: <a href="async_hooks.html#async_hookscreatehookcallbacks" class="type">&#x3C;AsyncHook></a> Instance used for disabling and enabling hooks</li>
489</ul>
490<p>Registers functions to be called for different lifetime events of each async
491operation.</p>
492<p>The callbacks <code>init()</code>/<code>before()</code>/<code>after()</code>/<code>destroy()</code> are called for the
493respective asynchronous event during a resource's lifetime.</p>
494<p>All callbacks are optional. For example, if only resource cleanup needs to
495be tracked, then only the <code>destroy</code> callback needs to be passed. The
496specifics of all functions that can be passed to <code>callbacks</code> is in the
497<a href="#hook-callbacks">Hook Callbacks</a> section.</p>
498
499<pre class="with-48-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createHook } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
500
501<span class="hljs-keyword">const</span> asyncHook = <span class="hljs-title function_">createHook</span>({
502  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { },
503  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { },
504});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
505
506<span class="hljs-keyword">const</span> asyncHook = async_hooks.<span class="hljs-title function_">createHook</span>({
507  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { },
508  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { },
509});</code><button class="copy-button">copy</button></pre>
510<p>The callbacks will be inherited via the prototype chain:</p>
511<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MyAsyncCallbacks</span> {
512  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { }
513  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) {}
514}
515
516<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyAddedCallbacks</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">MyAsyncCallbacks</span> {
517  <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }
518  <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }
519}
520
521<span class="hljs-keyword">const</span> asyncHook = async_hooks.<span class="hljs-title function_">createHook</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">MyAddedCallbacks</span>());</code> <button class="copy-button">copy</button></pre>
522<p>Because promises are asynchronous resources whose lifecycle is tracked
523via the async hooks mechanism, the <code>init()</code>, <code>before()</code>, <code>after()</code>, and
524<code>destroy()</code> callbacks <em>must not</em> be async functions that return promises.</p>
525<h4>Error handling<span><a class="mark" href="#error-handling" id="error-handling">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_error_handling"></a></h4>
526<p>If any <code>AsyncHook</code> callbacks throw, the application will print the stack trace
527and exit. The exit path does follow that of an uncaught exception, but
528all <code>'uncaughtException'</code> listeners are removed, thus forcing the process to
529exit. The <code>'exit'</code> callbacks will still be called unless the application is run
530with <code>--abort-on-uncaught-exception</code>, in which case a stack trace will be
531printed and the application exits, leaving a core file.</p>
532<p>The reason for this error handling behavior is that these callbacks are running
533at potentially volatile points in an object's lifetime, for example during
534class construction and destruction. Because of this, it is deemed necessary to
535bring down the process quickly in order to prevent an unintentional abort in the
536future. This is subject to change in the future if a comprehensive analysis is
537performed to ensure an exception can follow the normal control flow without
538unintentional side effects.</p>
539<h4>Printing in <code>AsyncHook</code> callbacks<span><a class="mark" href="#printing-in-asynchook-callbacks" id="printing-in-asynchook-callbacks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_printing_in_asynchook_callbacks"></a></h4>
540<p>Because printing to the console is an asynchronous operation, <code>console.log()</code>
541will cause <code>AsyncHook</code> callbacks to be called. Using <code>console.log()</code> or
542similar asynchronous operations inside an <code>AsyncHook</code> callback function will
543cause an infinite recursion. An easy solution to this when debugging is to use a
544synchronous logging operation such as <code>fs.writeFileSync(file, msg, flag)</code>.
545This will print to the file and will not invoke <code>AsyncHook</code> recursively because
546it is synchronous.</p>
547
548<pre class="with-40-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { writeFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
549<span class="hljs-keyword">import</span> { format } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
550
551<span class="hljs-keyword">function</span> <span class="hljs-title function_">debug</span>(<span class="hljs-params">...args</span>) {
552  <span class="hljs-comment">// Use a function like this one when debugging inside an AsyncHook callback</span>
553  <span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'log.out'</span>, <span class="hljs-string">`<span class="hljs-subst">${format(...args)}</span>\n`</span>, { <span class="hljs-attr">flag</span>: <span class="hljs-string">'a'</span> });
554}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
555<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
556
557<span class="hljs-keyword">function</span> <span class="hljs-title function_">debug</span>(<span class="hljs-params">...args</span>) {
558  <span class="hljs-comment">// Use a function like this one when debugging inside an AsyncHook callback</span>
559  fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'log.out'</span>, <span class="hljs-string">`<span class="hljs-subst">${util.format(...args)}</span>\n`</span>, { <span class="hljs-attr">flag</span>: <span class="hljs-string">'a'</span> });
560}</code><button class="copy-button">copy</button></pre>
561<p>If an asynchronous operation is needed for logging, it is possible to keep
562track of what caused the asynchronous operation using the information
563provided by <code>AsyncHook</code> itself. The logging should then be skipped when
564it was the logging itself that caused the <code>AsyncHook</code> callback to be called. By
565doing this, the otherwise infinite recursion is broken.</p>
566</section><section><h3>Class: <code>AsyncHook</code><span><a class="mark" href="#class-asynchook" id="class-asynchook">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_class_asynchook"></a></h3>
567<p>The class <code>AsyncHook</code> exposes an interface for tracking lifetime events
568of asynchronous operations.</p>
569<h4><code>asyncHook.enable()</code><span><a class="mark" href="#asynchookenable" id="asynchookenable">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_asynchook_enable"></a></h4>
570<ul>
571<li>Returns: <a href="async_hooks.html#async_hookscreatehookcallbacks" class="type">&#x3C;AsyncHook></a> A reference to <code>asyncHook</code>.</li>
572</ul>
573<p>Enable the callbacks for a given <code>AsyncHook</code> instance. If no callbacks are
574provided, enabling is a no-op.</p>
575<p>The <code>AsyncHook</code> instance is disabled by default. If the <code>AsyncHook</code> instance
576should be enabled immediately after creation, the following pattern can be used.</p>
577
578<pre class="with-48-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createHook } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
579
580<span class="hljs-keyword">const</span> hook = <span class="hljs-title function_">createHook</span>(callbacks).<span class="hljs-title function_">enable</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
581
582<span class="hljs-keyword">const</span> hook = async_hooks.<span class="hljs-title function_">createHook</span>(callbacks).<span class="hljs-title function_">enable</span>();</code><button class="copy-button">copy</button></pre>
583<h4><code>asyncHook.disable()</code><span><a class="mark" href="#asynchookdisable" id="asynchookdisable">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_asynchook_disable"></a></h4>
584<ul>
585<li>Returns: <a href="async_hooks.html#async_hookscreatehookcallbacks" class="type">&#x3C;AsyncHook></a> A reference to <code>asyncHook</code>.</li>
586</ul>
587<p>Disable the callbacks for a given <code>AsyncHook</code> instance from the global pool of
588<code>AsyncHook</code> callbacks to be executed. Once a hook has been disabled it will not
589be called again until enabled.</p>
590<p>For API consistency <code>disable()</code> also returns the <code>AsyncHook</code> instance.</p>
591<h4>Hook callbacks<span><a class="mark" href="#hook-callbacks" id="hook-callbacks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_hook_callbacks"></a></h4>
592<p>Key events in the lifetime of asynchronous events have been categorized into
593four areas: instantiation, before/after the callback is called, and when the
594instance is destroyed.</p>
595<h5><code>init(asyncId, type, triggerAsyncId, resource)</code><span><a class="mark" href="#initasyncid-type-triggerasyncid-resource" id="initasyncid-type-triggerasyncid-resource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_init_asyncid_type_triggerasyncid_resource"></a></h5>
596<ul>
597<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> A unique ID for the async resource.</li>
598<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The type of the async resource.</li>
599<li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The unique ID of the async resource in whose
600execution context this async resource was created.</li>
601<li><code>resource</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Reference to the resource representing the async
602operation, needs to be released during <em>destroy</em>.</li>
603</ul>
604<p>Called when a class is constructed that has the <em>possibility</em> to emit an
605asynchronous event. This <em>does not</em> mean the instance must call
606<code>before</code>/<code>after</code> before <code>destroy</code> is called, only that the possibility
607exists.</p>
608<p>This behavior can be observed by doing something like opening a resource then
609closing it before the resource can be used. The following snippet demonstrates
610this.</p>
611
612<pre class="with-72-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
613
614<span class="hljs-title function_">createServer</span>().<span class="hljs-title function_">listen</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">close</span>(); });
615<span class="hljs-comment">// OR</span>
616<span class="hljs-built_in">clearTimeout</span>(<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">10</span>));</code><code class="language-js cjs"><span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>).<span class="hljs-title function_">createServer</span>().<span class="hljs-title function_">listen</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">close</span>(); });
617<span class="hljs-comment">// OR</span>
618<span class="hljs-built_in">clearTimeout</span>(<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">10</span>));</code><button class="copy-button">copy</button></pre>
619<p>Every new resource is assigned an ID that is unique within the scope of the
620current Node.js instance.</p>
621<h6><code>type</code><span><a class="mark" href="#type" id="type">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_type"></a></h6>
622<p>The <code>type</code> is a string identifying the type of resource that caused
623<code>init</code> to be called. Generally, it will correspond to the name of the
624resource's constructor.</p>
625<p>The <code>type</code> of resources created by Node.js itself can change in any Node.js
626release. Valid values include <code>TLSWRAP</code>,
627<code>TCPWRAP</code>, <code>TCPSERVERWRAP</code>, <code>GETADDRINFOREQWRAP</code>, <code>FSREQCALLBACK</code>,
628<code>Microtask</code>, and <code>Timeout</code>. Inspect the source code of the Node.js version used
629to get the full list.</p>
630<p>Furthermore users of <a href="async_context.html#class-asyncresource"><code>AsyncResource</code></a> create async resources independent
631of Node.js itself.</p>
632<p>There is also the <code>PROMISE</code> resource type, which is used to track <code>Promise</code>
633instances and asynchronous work scheduled by them.</p>
634<p>Users are able to define their own <code>type</code> when using the public embedder API.</p>
635<p>It is possible to have type name collisions. Embedders are encouraged to use
636unique prefixes, such as the npm package name, to prevent collisions when
637listening to the hooks.</p>
638<h6><code>triggerAsyncId</code><span><a class="mark" href="#triggerasyncid" id="triggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_triggerasyncid"></a></h6>
639<p><code>triggerAsyncId</code> is the <code>asyncId</code> of the resource that caused (or "triggered")
640the new resource to initialize and that caused <code>init</code> to call. This is different
641from <code>async_hooks.executionAsyncId()</code> that only shows <em>when</em> a resource was
642created, while <code>triggerAsyncId</code> shows <em>why</em> a resource was created.</p>
643<p>The following is a simple demonstration of <code>triggerAsyncId</code>:</p>
644
645<pre class="with-69-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createHook, executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
646<span class="hljs-keyword">import</span> { stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
647<span class="hljs-keyword">import</span> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
648<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
649
650<span class="hljs-title function_">createHook</span>({
651  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
652    <span class="hljs-keyword">const</span> eid = <span class="hljs-title function_">executionAsyncId</span>();
653    fs.<span class="hljs-title function_">writeSync</span>(
654      stdout.<span class="hljs-property">fd</span>,
655      <span class="hljs-string">`<span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>): trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
656  },
657}).<span class="hljs-title function_">enable</span>();
658
659net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createHook, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
660<span class="hljs-keyword">const</span> { stdout } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
661<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
662<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
663
664<span class="hljs-title function_">createHook</span>({
665  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
666    <span class="hljs-keyword">const</span> eid = <span class="hljs-title function_">executionAsyncId</span>();
667    fs.<span class="hljs-title function_">writeSync</span>(
668      stdout.<span class="hljs-property">fd</span>,
669      <span class="hljs-string">`<span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>): trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
670  },
671}).<span class="hljs-title function_">enable</span>();
672
673net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);</code><button class="copy-button">copy</button></pre>
674<p>Output when hitting the server with <code>nc localhost 8080</code>:</p>
675<pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1
676TCPWRAP(7): trigger: 5 execution: 0</code> <button class="copy-button">copy</button></pre>
677<p>The <code>TCPSERVERWRAP</code> is the server which receives the connections.</p>
678<p>The <code>TCPWRAP</code> is the new connection from the client. When a new
679connection is made, the <code>TCPWrap</code> instance is immediately constructed. This
680happens outside of any JavaScript stack. (An <code>executionAsyncId()</code> of <code>0</code> means
681that it is being executed from C++ with no JavaScript stack above it.) With only
682that information, it would be impossible to link resources together in
683terms of what caused them to be created, so <code>triggerAsyncId</code> is given the task
684of propagating what resource is responsible for the new resource's existence.</p>
685<h6><code>resource</code><span><a class="mark" href="#resource" id="resource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_resource"></a></h6>
686<p><code>resource</code> is an object that represents the actual async resource that has
687been initialized. The API to access the object may be specified by the
688creator of the resource. Resources created by Node.js itself are internal
689and may change at any time. Therefore no API is specified for these.</p>
690<p>In some cases the resource object is reused for performance reasons, it is
691thus not safe to use it as a key in a <code>WeakMap</code> or add properties to it.</p>
692<h6>Asynchronous context example<span><a class="mark" href="#asynchronous-context-example" id="asynchronous-context-example">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_asynchronous_context_example"></a></h6>
693<p>The context tracking use case is covered by the stable API <a href="async_context.html#class-asynclocalstorage"><code>AsyncLocalStorage</code></a>.
694This example only illustrates async hooks operation but <a href="async_context.html#class-asynclocalstorage"><code>AsyncLocalStorage</code></a>
695fits better to this use case.</p>
696<p>The following is an example with additional information about the calls to
697<code>init</code> between the <code>before</code> and <code>after</code> calls, specifically what the
698callback to <code>listen()</code> will look like. The output formatting is slightly more
699elaborate to make calling context easier to see.</p>
700
701<pre class="with-48-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> async_hooks <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
702<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
703<span class="hljs-keyword">import</span> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
704<span class="hljs-keyword">import</span> { stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
705<span class="hljs-keyword">const</span> { fd } = stdout;
706
707<span class="hljs-keyword">let</span> indent = <span class="hljs-number">0</span>;
708async_hooks.<span class="hljs-title function_">createHook</span>({
709  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
710    <span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
711    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
712    fs.<span class="hljs-title function_">writeSync</span>(
713      fd,
714      <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span><span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>):`</span> +
715      <span class="hljs-string">` trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
716  },
717  <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) {
718    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
719    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>before:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
720    indent += <span class="hljs-number">2</span>;
721  },
722  <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) {
723    indent -= <span class="hljs-number">2</span>;
724    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
725    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>after:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
726  },
727  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) {
728    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
729    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>destroy:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
730  },
731}).<span class="hljs-title function_">enable</span>();
732
733net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">() =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>, <span class="hljs-function">() =></span> {
734  <span class="hljs-comment">// Let's wait 10ms before logging the server started.</span>
735  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
736    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'>>>'</span>, async_hooks.<span class="hljs-title function_">executionAsyncId</span>());
737  }, <span class="hljs-number">10</span>);
738});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
739<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
740<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
741<span class="hljs-keyword">const</span> { fd } = process.<span class="hljs-property">stdout</span>;
742
743<span class="hljs-keyword">let</span> indent = <span class="hljs-number">0</span>;
744async_hooks.<span class="hljs-title function_">createHook</span>({
745  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
746    <span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
747    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
748    fs.<span class="hljs-title function_">writeSync</span>(
749      fd,
750      <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span><span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>):`</span> +
751      <span class="hljs-string">` trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
752  },
753  <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) {
754    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
755    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>before:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
756    indent += <span class="hljs-number">2</span>;
757  },
758  <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) {
759    indent -= <span class="hljs-number">2</span>;
760    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
761    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>after:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
762  },
763  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) {
764    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
765    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>destroy:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
766  },
767}).<span class="hljs-title function_">enable</span>();
768
769net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">() =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>, <span class="hljs-function">() =></span> {
770  <span class="hljs-comment">// Let's wait 10ms before logging the server started.</span>
771  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
772    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'>>>'</span>, async_hooks.<span class="hljs-title function_">executionAsyncId</span>());
773  }, <span class="hljs-number">10</span>);
774});</code><button class="copy-button">copy</button></pre>
775<p>Output from only starting the server:</p>
776<pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1
777TickObject(6): trigger: 5 execution: 1
778before:  6
779  Timeout(7): trigger: 6 execution: 6
780after:   6
781destroy: 6
782before:  7
783<span class="hljs-meta prompt_">></span><span class="language-bash">>> 7</span>
784  TickObject(8): trigger: 7 execution: 7
785after:   7
786before:  8
787after:   8</code> <button class="copy-button">copy</button></pre>
788<p>As illustrated in the example, <code>executionAsyncId()</code> and <code>execution</code> each specify
789the value of the current execution context; which is delineated by calls to
790<code>before</code> and <code>after</code>.</p>
791<p>Only using <code>execution</code> to graph resource allocation results in the following:</p>
792<pre><code class="language-console">  root(1)
793     ^
794     |
795TickObject(6)
796     ^
797     |
798 Timeout(7)</code> <button class="copy-button">copy</button></pre>
799<p>The <code>TCPSERVERWRAP</code> is not part of this graph, even though it was the reason for
800<code>console.log()</code> being called. This is because binding to a port without a host
801name is a <em>synchronous</em> operation, but to maintain a completely asynchronous
802API the user's callback is placed in a <code>process.nextTick()</code>. Which is why
803<code>TickObject</code> is present in the output and is a 'parent' for <code>.listen()</code>
804callback.</p>
805<p>The graph only shows <em>when</em> a resource was created, not <em>why</em>, so to track
806the <em>why</em> use <code>triggerAsyncId</code>. Which can be represented with the following
807graph:</p>
808<pre><code class="language-console"> bootstrap(1)
809     |
810     ˅
811TCPSERVERWRAP(5)
812     |
813     ˅
814 TickObject(6)
815     |
816     ˅
817  Timeout(7)</code> <button class="copy-button">copy</button></pre>
818<h5><code>before(asyncId)</code><span><a class="mark" href="#beforeasyncid" id="beforeasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_before_asyncid"></a></h5>
819<ul>
820<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
821</ul>
822<p>When an asynchronous operation is initiated (such as a TCP server receiving a
823new connection) or completes (such as writing data to disk) a callback is
824called to notify the user. The <code>before</code> callback is called just before said
825callback is executed. <code>asyncId</code> is the unique identifier assigned to the
826resource about to execute the callback.</p>
827<p>The <code>before</code> callback will be called 0 to N times. The <code>before</code> callback
828will typically be called 0 times if the asynchronous operation was cancelled
829or, for example, if no connections are received by a TCP server. Persistent
830asynchronous resources like a TCP server will typically call the <code>before</code>
831callback multiple times, while other operations like <code>fs.open()</code> will call
832it only once.</p>
833<h5><code>after(asyncId)</code><span><a class="mark" href="#afterasyncid" id="afterasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_after_asyncid"></a></h5>
834<ul>
835<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
836</ul>
837<p>Called immediately after the callback specified in <code>before</code> is completed.</p>
838<p>If an uncaught exception occurs during execution of the callback, then <code>after</code>
839will run <em>after</em> the <code>'uncaughtException'</code> event is emitted or a <code>domain</code>'s
840handler runs.</p>
841<h5><code>destroy(asyncId)</code><span><a class="mark" href="#destroyasyncid" id="destroyasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_destroy_asyncid"></a></h5>
842<ul>
843<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
844</ul>
845<p>Called after the resource corresponding to <code>asyncId</code> is destroyed. It is also
846called asynchronously from the embedder API <code>emitDestroy()</code>.</p>
847<p>Some resources depend on garbage collection for cleanup, so if a reference is
848made to the <code>resource</code> object passed to <code>init</code> it is possible that <code>destroy</code>
849will never be called, causing a memory leak in the application. If the resource
850does not depend on garbage collection, then this will not be an issue.</p>
851<p>Using the destroy hook results in additional overhead because it enables
852tracking of <code>Promise</code> instances via the garbage collector.</p>
853<h5><code>promiseResolve(asyncId)</code><span><a class="mark" href="#promiseresolveasyncid" id="promiseresolveasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_promiseresolve_asyncid"></a></h5>
854<div class="api_metadata">
855<span>Added in: v8.6.0</span>
856</div>
857<ul>
858<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
859</ul>
860<p>Called when the <code>resolve</code> function passed to the <code>Promise</code> constructor is
861invoked (either directly or through other means of resolving a promise).</p>
862<p><code>resolve()</code> does not do any observable synchronous work.</p>
863<p>The <code>Promise</code> is not necessarily fulfilled or rejected at this point if the
864<code>Promise</code> was resolved by assuming the state of another <code>Promise</code>.</p>
865<pre><code class="language-js"><span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =></span> <span class="hljs-title function_">resolve</span>(<span class="hljs-literal">true</span>)).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> {});</code> <button class="copy-button">copy</button></pre>
866<p>calls the following callbacks:</p>
867<pre><code class="language-text">init for PROMISE with id 5, trigger id: 1
868  promise resolve 5      # corresponds to resolve(true)
869init for PROMISE with id 6, trigger id: 5  # the Promise returned by then()
870  before 6               # the then() callback is entered
871  promise resolve 6      # the then() callback resolves the promise by returning
872  after 6</code> <button class="copy-button">copy</button></pre>
873<h4><code>async_hooks.executionAsyncResource()</code><span><a class="mark" href="#async_hooksexecutionasyncresource" id="async_hooksexecutionasyncresource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_executionasyncresource"></a></h4>
874<div class="api_metadata">
875<span>Added in: v13.9.0, v12.17.0</span>
876</div>
877<ul>
878<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The resource representing the current execution.
879Useful to store data within the resource.</li>
880</ul>
881<p>Resource objects returned by <code>executionAsyncResource()</code> are most often internal
882Node.js handle objects with undocumented APIs. Using any functions or properties
883on the object is likely to crash your application and should be avoided.</p>
884<p>Using <code>executionAsyncResource()</code> in the top-level execution context will
885return an empty object as there is no handle or request object to use,
886but having an object representing the top-level can be helpful.</p>
887
888<pre class="with-81-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
889<span class="hljs-keyword">import</span> { executionAsyncId, executionAsyncResource } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
890
891<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>());  <span class="hljs-comment">// 1 {}</span>
892<span class="hljs-title function_">open</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>), <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
893  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>());  <span class="hljs-comment">// 7 FSReqWrap</span>
894});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { open } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
895<span class="hljs-keyword">const</span> { executionAsyncId, executionAsyncResource } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
896
897<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>());  <span class="hljs-comment">// 1 {}</span>
898<span class="hljs-title function_">open</span>(__filename, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
899  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>());  <span class="hljs-comment">// 7 FSReqWrap</span>
900});</code><button class="copy-button">copy</button></pre>
901<p>This can be used to implement continuation local storage without the
902use of a tracking <code>Map</code> to store the metadata:</p>
903
904<pre class="with-46-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
905<span class="hljs-keyword">import</span> {
906  executionAsyncId,
907  executionAsyncResource,
908  createHook,
909} <span class="hljs-keyword">from</span> <span class="hljs-string">'async_hooks'</span>;
910<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'state'</span>); <span class="hljs-comment">// Private symbol to avoid pollution</span>
911
912<span class="hljs-title function_">createHook</span>({
913  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) {
914    <span class="hljs-keyword">const</span> cr = <span class="hljs-title function_">executionAsyncResource</span>();
915    <span class="hljs-keyword">if</span> (cr) {
916      resource[sym] = cr[sym];
917    }
918  },
919}).<span class="hljs-title function_">enable</span>();
920
921<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
922  <span class="hljs-title function_">executionAsyncResource</span>()[sym] = { <span class="hljs-attr">state</span>: req.<span class="hljs-property">url</span> };
923  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
924    res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(<span class="hljs-title function_">executionAsyncResource</span>()[sym]));
925  }, <span class="hljs-number">100</span>);
926}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
927<span class="hljs-keyword">const</span> {
928  executionAsyncId,
929  executionAsyncResource,
930  createHook,
931} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
932<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'state'</span>); <span class="hljs-comment">// Private symbol to avoid pollution</span>
933
934<span class="hljs-title function_">createHook</span>({
935  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) {
936    <span class="hljs-keyword">const</span> cr = <span class="hljs-title function_">executionAsyncResource</span>();
937    <span class="hljs-keyword">if</span> (cr) {
938      resource[sym] = cr[sym];
939    }
940  },
941}).<span class="hljs-title function_">enable</span>();
942
943<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
944  <span class="hljs-title function_">executionAsyncResource</span>()[sym] = { <span class="hljs-attr">state</span>: req.<span class="hljs-property">url</span> };
945  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
946    res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(<span class="hljs-title function_">executionAsyncResource</span>()[sym]));
947  }, <span class="hljs-number">100</span>);
948}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre>
949<h4><code>async_hooks.executionAsyncId()</code><span><a class="mark" href="#async_hooksexecutionasyncid" id="async_hooksexecutionasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_executionasyncid"></a></h4>
950<div class="api_metadata">
951<details class="changelog"><summary>History</summary>
952<table>
953<tbody><tr><th>Version</th><th>Changes</th></tr>
954<tr><td>v8.2.0</td>
955<td><p>Renamed from <code>currentId</code>.</p></td></tr>
956<tr><td>v8.1.0</td>
957<td><p><span>Added in: v8.1.0</span></p></td></tr>
958</tbody></table>
959</details>
960</div>
961<ul>
962<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The <code>asyncId</code> of the current execution context. Useful to
963track when something calls.</li>
964</ul>
965
966<pre class="with-52-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
967<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
968
969<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>());  <span class="hljs-comment">// 1 - bootstrap</span>
970<span class="hljs-keyword">const</span> path = <span class="hljs-string">'.'</span>;
971fs.<span class="hljs-title function_">open</span>(path, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
972  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>());  <span class="hljs-comment">// 6 - open()</span>
973});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
974<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
975
976<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(async_hooks.<span class="hljs-title function_">executionAsyncId</span>());  <span class="hljs-comment">// 1 - bootstrap</span>
977<span class="hljs-keyword">const</span> path = <span class="hljs-string">'.'</span>;
978fs.<span class="hljs-title function_">open</span>(path, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
979  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(async_hooks.<span class="hljs-title function_">executionAsyncId</span>());  <span class="hljs-comment">// 6 - open()</span>
980});</code><button class="copy-button">copy</button></pre>
981<p>The ID returned from <code>executionAsyncId()</code> is related to execution timing, not
982causality (which is covered by <code>triggerAsyncId()</code>):</p>
983<pre><code class="language-js"><span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {
984  <span class="hljs-comment">// Returns the ID of the server, not of the new connection, because the</span>
985  <span class="hljs-comment">// callback runs in the execution scope of the server's MakeCallback().</span>
986  async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
987
988}).<span class="hljs-title function_">listen</span>(port, <span class="hljs-function">() =></span> {
989  <span class="hljs-comment">// Returns the ID of a TickObject (process.nextTick()) because all</span>
990  <span class="hljs-comment">// callbacks passed to .listen() are wrapped in a nextTick().</span>
991  async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
992});</code> <button class="copy-button">copy</button></pre>
993<p>Promise contexts may not get precise <code>executionAsyncIds</code> by default.
994See the section on <a href="#promise-execution-tracking">promise execution tracking</a>.</p>
995<h4><code>async_hooks.triggerAsyncId()</code><span><a class="mark" href="#async_hookstriggerasyncid" id="async_hookstriggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_triggerasyncid"></a></h4>
996<ul>
997<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The ID of the resource responsible for calling the callback
998that is currently being executed.</li>
999</ul>
1000<pre><code class="language-js"><span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {
1001  <span class="hljs-comment">// The resource that caused (or triggered) this callback to be called</span>
1002  <span class="hljs-comment">// was that of the new connection. Thus the return value of triggerAsyncId()</span>
1003  <span class="hljs-comment">// is the asyncId of "conn".</span>
1004  async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
1005
1006}).<span class="hljs-title function_">listen</span>(port, <span class="hljs-function">() =></span> {
1007  <span class="hljs-comment">// Even though all callbacks passed to .listen() are wrapped in a nextTick()</span>
1008  <span class="hljs-comment">// the callback itself exists because the call to the server's .listen()</span>
1009  <span class="hljs-comment">// was made. So the return value would be the ID of the server.</span>
1010  async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
1011});</code> <button class="copy-button">copy</button></pre>
1012<p>Promise contexts may not get valid <code>triggerAsyncId</code>s by default. See
1013the section on <a href="#promise-execution-tracking">promise execution tracking</a>.</p>
1014<h4><code>async_hooks.asyncWrapProviders</code><span><a class="mark" href="#async_hooksasyncwrapproviders" id="async_hooksasyncwrapproviders">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_asyncwrapproviders"></a></h4>
1015<div class="api_metadata">
1016<span>Added in: v17.2.0, v16.14.0</span>
1017</div>
1018<ul>
1019<li>Returns: A map of provider types to the corresponding numeric id.
1020This map contains all the event types that might be emitted by the <code>async_hooks.init()</code> event.</li>
1021</ul>
1022<p>This feature suppresses the deprecated usage of <code>process.binding('async_wrap').Providers</code>.
1023See: <a href="deprecations.html#dep0111-processbinding">DEP0111</a></p>
1024</section><section><h3>Promise execution tracking<span><a class="mark" href="#promise-execution-tracking" id="promise-execution-tracking">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_promise_execution_tracking"></a></h3>
1025<p>By default, promise executions are not assigned <code>asyncId</code>s due to the relatively
1026expensive nature of the <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">promise introspection API</a> provided by
1027V8. This means that programs using promises or <code>async</code>/<code>await</code> will not get
1028correct execution and trigger ids for promise callback contexts by default.</p>
1029
1030<pre class="with-73-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { executionAsyncId, triggerAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
1031
1032<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
1033  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
1034});
1035<span class="hljs-comment">// produces:</span>
1036<span class="hljs-comment">// eid 1 tid 0</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { executionAsyncId, triggerAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
1037
1038<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
1039  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
1040});
1041<span class="hljs-comment">// produces:</span>
1042<span class="hljs-comment">// eid 1 tid 0</span></code><button class="copy-button">copy</button></pre>
1043<p>Observe that the <code>then()</code> callback claims to have executed in the context of the
1044outer scope even though there was an asynchronous hop involved. Also,
1045the <code>triggerAsyncId</code> value is <code>0</code>, which means that we are missing context about
1046the resource that caused (triggered) the <code>then()</code> callback to be executed.</p>
1047<p>Installing async hooks via <code>async_hooks.createHook</code> enables promise execution
1048tracking:</p>
1049
1050<pre class="with-85-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createHook, executionAsyncId, triggerAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
1051<span class="hljs-title function_">createHook</span>({ <span class="hljs-title function_">init</span>(<span class="hljs-params"></span>) {} }).<span class="hljs-title function_">enable</span>(); <span class="hljs-comment">// forces PromiseHooks to be enabled.</span>
1052<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
1053  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
1054});
1055<span class="hljs-comment">// produces:</span>
1056<span class="hljs-comment">// eid 7 tid 6</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createHook, executionAsyncId, triggerAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
1057
1058<span class="hljs-title function_">createHook</span>({ <span class="hljs-title function_">init</span>(<span class="hljs-params"></span>) {} }).<span class="hljs-title function_">enable</span>(); <span class="hljs-comment">// forces PromiseHooks to be enabled.</span>
1059<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
1060  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
1061});
1062<span class="hljs-comment">// produces:</span>
1063<span class="hljs-comment">// eid 7 tid 6</span></code><button class="copy-button">copy</button></pre>
1064<p>In this example, adding any actual hook function enabled the tracking of
1065promises. There are two promises in the example above; the promise created by
1066<code>Promise.resolve()</code> and the promise returned by the call to <code>then()</code>. In the
1067example above, the first promise got the <code>asyncId</code> <code>6</code> and the latter got
1068<code>asyncId</code> <code>7</code>. During the execution of the <code>then()</code> callback, we are executing
1069in the context of promise with <code>asyncId</code> <code>7</code>. This promise was triggered by
1070async resource <code>6</code>.</p>
1071<p>Another subtlety with promises is that <code>before</code> and <code>after</code> callbacks are run
1072only on chained promises. That means promises not created by <code>then()</code>/<code>catch()</code>
1073will not have the <code>before</code> and <code>after</code> callbacks fired on them. For more details
1074see the details of the V8 <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">PromiseHooks</a> API.</p>
1075</section><section><h3>JavaScript embedder API<span><a class="mark" href="#javascript-embedder-api" id="javascript-embedder-api">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_javascript_embedder_api"></a></h3>
1076<p>Library developers that handle their own asynchronous resources performing tasks
1077like I/O, connection pooling, or managing callback queues may use the
1078<code>AsyncResource</code> JavaScript API so that all the appropriate callbacks are called.</p>
1079<h4>Class: <code>AsyncResource</code><span><a class="mark" href="#class-asyncresource" id="class-asyncresource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_class_asyncresource"></a></h4>
1080<p>The documentation for this class has moved <a href="async_context.html#class-asyncresource"><code>AsyncResource</code></a>.</p>
1081</section><section><h3>Class: <code>AsyncLocalStorage</code><span><a class="mark" href="#class-asynclocalstorage" id="class-asynclocalstorage">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_class_asynclocalstorage"></a></h3>
1082<p>The documentation for this class has moved <a href="async_context.html#class-asynclocalstorage"><code>AsyncLocalStorage</code></a>.</p></section>
1083        <!-- API END -->
1084      </div>
1085    </div>
1086  </div>
1087</body>
1088</html>
1089