11cb0ef41Sopenharmony_ci<!DOCTYPE html>
21cb0ef41Sopenharmony_ci<html lang="en">
31cb0ef41Sopenharmony_ci<head>
41cb0ef41Sopenharmony_ci  <meta charset="utf-8">
51cb0ef41Sopenharmony_ci  <meta name="viewport" content="width=device-width">
61cb0ef41Sopenharmony_ci  <meta name="nodejs.org:node-version" content="v18.20.1">
71cb0ef41Sopenharmony_ci  <title>Asynchronous context tracking | Node.js v18.20.1 Documentation</title>
81cb0ef41Sopenharmony_ci  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
91cb0ef41Sopenharmony_ci  <link rel="stylesheet" href="assets/style.css">
101cb0ef41Sopenharmony_ci  <link rel="stylesheet" href="assets/hljs.css">
111cb0ef41Sopenharmony_ci  <link rel="canonical" href="https://nodejs.org/api/async_context.html">
121cb0ef41Sopenharmony_ci  <script async defer src="assets/api.js" type="text/javascript"></script>
131cb0ef41Sopenharmony_ci  <style>@media(max-width:1080px){.with-73-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:686px){.with-58-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:654px){.with-54-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:598px){.with-47-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}</style>
141cb0ef41Sopenharmony_ci</head>
151cb0ef41Sopenharmony_ci<body class="alt apidoc" id="api-section-async_context">
161cb0ef41Sopenharmony_ci  <div id="content" class="clearfix">
171cb0ef41Sopenharmony_ci    <div id="column2" class="interior">
181cb0ef41Sopenharmony_ci      <div id="intro" class="interior">
191cb0ef41Sopenharmony_ci        <a href="/" title="Go back to the home page">
201cb0ef41Sopenharmony_ci          Node.js
211cb0ef41Sopenharmony_ci        </a>
221cb0ef41Sopenharmony_ci      </div>
231cb0ef41Sopenharmony_ci      <ul>
241cb0ef41Sopenharmony_ci<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
251cb0ef41Sopenharmony_ci<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
261cb0ef41Sopenharmony_ci</ul>
271cb0ef41Sopenharmony_ci<hr class="line">
281cb0ef41Sopenharmony_ci<ul>
291cb0ef41Sopenharmony_ci<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
301cb0ef41Sopenharmony_ci<li><a href="async_context.html" class="nav-async_context active">Asynchronous context tracking</a></li>
311cb0ef41Sopenharmony_ci<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
321cb0ef41Sopenharmony_ci<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
331cb0ef41Sopenharmony_ci<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
341cb0ef41Sopenharmony_ci<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
351cb0ef41Sopenharmony_ci<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
361cb0ef41Sopenharmony_ci<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
371cb0ef41Sopenharmony_ci<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
381cb0ef41Sopenharmony_ci<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
391cb0ef41Sopenharmony_ci<li><a href="console.html" class="nav-console">Console</a></li>
401cb0ef41Sopenharmony_ci<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
411cb0ef41Sopenharmony_ci<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
421cb0ef41Sopenharmony_ci<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
431cb0ef41Sopenharmony_ci<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
441cb0ef41Sopenharmony_ci<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
451cb0ef41Sopenharmony_ci<li><a href="dns.html" class="nav-dns">DNS</a></li>
461cb0ef41Sopenharmony_ci<li><a href="domain.html" class="nav-domain">Domain</a></li>
471cb0ef41Sopenharmony_ci<li><a href="errors.html" class="nav-errors">Errors</a></li>
481cb0ef41Sopenharmony_ci<li><a href="events.html" class="nav-events">Events</a></li>
491cb0ef41Sopenharmony_ci<li><a href="fs.html" class="nav-fs">File system</a></li>
501cb0ef41Sopenharmony_ci<li><a href="globals.html" class="nav-globals">Globals</a></li>
511cb0ef41Sopenharmony_ci<li><a href="http.html" class="nav-http">HTTP</a></li>
521cb0ef41Sopenharmony_ci<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
531cb0ef41Sopenharmony_ci<li><a href="https.html" class="nav-https">HTTPS</a></li>
541cb0ef41Sopenharmony_ci<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
551cb0ef41Sopenharmony_ci<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
561cb0ef41Sopenharmony_ci<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
571cb0ef41Sopenharmony_ci<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
581cb0ef41Sopenharmony_ci<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
591cb0ef41Sopenharmony_ci<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
601cb0ef41Sopenharmony_ci<li><a href="net.html" class="nav-net">Net</a></li>
611cb0ef41Sopenharmony_ci<li><a href="os.html" class="nav-os">OS</a></li>
621cb0ef41Sopenharmony_ci<li><a href="path.html" class="nav-path">Path</a></li>
631cb0ef41Sopenharmony_ci<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
641cb0ef41Sopenharmony_ci<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
651cb0ef41Sopenharmony_ci<li><a href="process.html" class="nav-process">Process</a></li>
661cb0ef41Sopenharmony_ci<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
671cb0ef41Sopenharmony_ci<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
681cb0ef41Sopenharmony_ci<li><a href="readline.html" class="nav-readline">Readline</a></li>
691cb0ef41Sopenharmony_ci<li><a href="repl.html" class="nav-repl">REPL</a></li>
701cb0ef41Sopenharmony_ci<li><a href="report.html" class="nav-report">Report</a></li>
711cb0ef41Sopenharmony_ci<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
721cb0ef41Sopenharmony_ci<li><a href="stream.html" class="nav-stream">Stream</a></li>
731cb0ef41Sopenharmony_ci<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
741cb0ef41Sopenharmony_ci<li><a href="test.html" class="nav-test">Test runner</a></li>
751cb0ef41Sopenharmony_ci<li><a href="timers.html" class="nav-timers">Timers</a></li>
761cb0ef41Sopenharmony_ci<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
771cb0ef41Sopenharmony_ci<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
781cb0ef41Sopenharmony_ci<li><a href="tty.html" class="nav-tty">TTY</a></li>
791cb0ef41Sopenharmony_ci<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
801cb0ef41Sopenharmony_ci<li><a href="url.html" class="nav-url">URL</a></li>
811cb0ef41Sopenharmony_ci<li><a href="util.html" class="nav-util">Utilities</a></li>
821cb0ef41Sopenharmony_ci<li><a href="v8.html" class="nav-v8">V8</a></li>
831cb0ef41Sopenharmony_ci<li><a href="vm.html" class="nav-vm">VM</a></li>
841cb0ef41Sopenharmony_ci<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
851cb0ef41Sopenharmony_ci<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
861cb0ef41Sopenharmony_ci<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
871cb0ef41Sopenharmony_ci<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
881cb0ef41Sopenharmony_ci<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
891cb0ef41Sopenharmony_ci</ul>
901cb0ef41Sopenharmony_ci<hr class="line">
911cb0ef41Sopenharmony_ci<ul>
921cb0ef41Sopenharmony_ci<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
931cb0ef41Sopenharmony_ci</ul>
941cb0ef41Sopenharmony_ci    </div>
951cb0ef41Sopenharmony_ci
961cb0ef41Sopenharmony_ci    <div id="column1" data-id="async_context" class="interior">
971cb0ef41Sopenharmony_ci      <header class="header">
981cb0ef41Sopenharmony_ci        <div class="header-container">
991cb0ef41Sopenharmony_ci          <h1>Node.js v18.20.1 documentation</h1>
1001cb0ef41Sopenharmony_ci          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
1011cb0ef41Sopenharmony_ci            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
1021cb0ef41Sopenharmony_ci              <path fill="none" d="M0 0h24v24H0z" />
1031cb0ef41Sopenharmony_ci              <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"/>
1041cb0ef41Sopenharmony_ci              <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"/>
1051cb0ef41Sopenharmony_ci            </svg>
1061cb0ef41Sopenharmony_ci            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
1071cb0ef41Sopenharmony_ci              <path d="M0 0h24v24H0z" fill="none" />
1081cb0ef41Sopenharmony_ci              <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"/>
1091cb0ef41Sopenharmony_ci            </svg>
1101cb0ef41Sopenharmony_ci          </button>
1111cb0ef41Sopenharmony_ci        </div>
1121cb0ef41Sopenharmony_ci        <div id="gtoc">
1131cb0ef41Sopenharmony_ci          <ul>
1141cb0ef41Sopenharmony_ci            <li class="pinned-header">Node.js v18.20.1</li>
1151cb0ef41Sopenharmony_ci            
1161cb0ef41Sopenharmony_ci    <li class="picker-header">
1171cb0ef41Sopenharmony_ci      <a href="#">
1181cb0ef41Sopenharmony_ci        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
1191cb0ef41Sopenharmony_ci        Table of contents
1201cb0ef41Sopenharmony_ci      </a>
1211cb0ef41Sopenharmony_ci
1221cb0ef41Sopenharmony_ci      <div class="picker"><div class="toc"><ul>
1231cb0ef41Sopenharmony_ci<li><span class="stability_2"><a href="#asynchronous-context-tracking">Asynchronous context tracking</a></span>
1241cb0ef41Sopenharmony_ci<ul>
1251cb0ef41Sopenharmony_ci<li><a href="#introduction">Introduction</a></li>
1261cb0ef41Sopenharmony_ci<li><a href="#class-asynclocalstorage">Class: <code>AsyncLocalStorage</code></a>
1271cb0ef41Sopenharmony_ci<ul>
1281cb0ef41Sopenharmony_ci<li><a href="#new-asynclocalstorage"><code>new AsyncLocalStorage()</code></a></li>
1291cb0ef41Sopenharmony_ci<li><span class="stability_1"><a href="#static-method-asynclocalstoragebindfn">Static method: <code>AsyncLocalStorage.bind(fn)</code></a></span></li>
1301cb0ef41Sopenharmony_ci<li><span class="stability_1"><a href="#static-method-asynclocalstoragesnapshot">Static method: <code>AsyncLocalStorage.snapshot()</code></a></span></li>
1311cb0ef41Sopenharmony_ci<li><span class="stability_1"><a href="#asynclocalstoragedisable"><code>asyncLocalStorage.disable()</code></a></span></li>
1321cb0ef41Sopenharmony_ci<li><a href="#asynclocalstoragegetstore"><code>asyncLocalStorage.getStore()</code></a></li>
1331cb0ef41Sopenharmony_ci<li><span class="stability_1"><a href="#asynclocalstorageenterwithstore"><code>asyncLocalStorage.enterWith(store)</code></a></span></li>
1341cb0ef41Sopenharmony_ci<li><a href="#asynclocalstoragerunstore-callback-args"><code>asyncLocalStorage.run(store, callback[, ...args])</code></a></li>
1351cb0ef41Sopenharmony_ci<li><span class="stability_1"><a href="#asynclocalstorageexitcallback-args"><code>asyncLocalStorage.exit(callback[, ...args])</code></a></span></li>
1361cb0ef41Sopenharmony_ci<li><a href="#usage-with-asyncawait">Usage with <code>async/await</code></a></li>
1371cb0ef41Sopenharmony_ci<li><a href="#troubleshooting-context-loss">Troubleshooting: Context loss</a></li>
1381cb0ef41Sopenharmony_ci</ul>
1391cb0ef41Sopenharmony_ci</li>
1401cb0ef41Sopenharmony_ci<li><a href="#class-asyncresource">Class: <code>AsyncResource</code></a>
1411cb0ef41Sopenharmony_ci<ul>
1421cb0ef41Sopenharmony_ci<li><a href="#new-asyncresourcetype-options"><code>new AsyncResource(type[, options])</code></a></li>
1431cb0ef41Sopenharmony_ci<li><a href="#static-method-asyncresourcebindfn-type-thisarg">Static method: <code>AsyncResource.bind(fn[, type[, thisArg]])</code></a></li>
1441cb0ef41Sopenharmony_ci<li><a href="#asyncresourcebindfn-thisarg"><code>asyncResource.bind(fn[, thisArg])</code></a></li>
1451cb0ef41Sopenharmony_ci<li><a href="#asyncresourceruninasyncscopefn-thisarg-args"><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code></a></li>
1461cb0ef41Sopenharmony_ci<li><a href="#asyncresourceemitdestroy"><code>asyncResource.emitDestroy()</code></a></li>
1471cb0ef41Sopenharmony_ci<li><a href="#asyncresourceasyncid"><code>asyncResource.asyncId()</code></a></li>
1481cb0ef41Sopenharmony_ci<li><a href="#asyncresourcetriggerasyncid"><code>asyncResource.triggerAsyncId()</code></a></li>
1491cb0ef41Sopenharmony_ci<li><a href="#using-asyncresource-for-a-worker-thread-pool">Using <code>AsyncResource</code> for a <code>Worker</code> thread pool</a></li>
1501cb0ef41Sopenharmony_ci<li><a href="#integrating-asyncresource-with-eventemitter">Integrating <code>AsyncResource</code> with <code>EventEmitter</code></a></li>
1511cb0ef41Sopenharmony_ci</ul>
1521cb0ef41Sopenharmony_ci</li>
1531cb0ef41Sopenharmony_ci</ul>
1541cb0ef41Sopenharmony_ci</li>
1551cb0ef41Sopenharmony_ci</ul></div></div>
1561cb0ef41Sopenharmony_ci    </li>
1571cb0ef41Sopenharmony_ci  
1581cb0ef41Sopenharmony_ci            
1591cb0ef41Sopenharmony_ci    <li class="picker-header">
1601cb0ef41Sopenharmony_ci      <a href="#">
1611cb0ef41Sopenharmony_ci        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
1621cb0ef41Sopenharmony_ci        Index
1631cb0ef41Sopenharmony_ci      </a>
1641cb0ef41Sopenharmony_ci
1651cb0ef41Sopenharmony_ci      <div class="picker"><ul>
1661cb0ef41Sopenharmony_ci<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
1671cb0ef41Sopenharmony_ci<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
1681cb0ef41Sopenharmony_ci
1691cb0ef41Sopenharmony_ci      <li>
1701cb0ef41Sopenharmony_ci        <a href="index.html">Index</a>
1711cb0ef41Sopenharmony_ci      </li>
1721cb0ef41Sopenharmony_ci    </ul>
1731cb0ef41Sopenharmony_ci  
1741cb0ef41Sopenharmony_ci<hr class="line">
1751cb0ef41Sopenharmony_ci<ul>
1761cb0ef41Sopenharmony_ci<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
1771cb0ef41Sopenharmony_ci<li><a href="async_context.html" class="nav-async_context active">Asynchronous context tracking</a></li>
1781cb0ef41Sopenharmony_ci<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
1791cb0ef41Sopenharmony_ci<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
1801cb0ef41Sopenharmony_ci<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
1811cb0ef41Sopenharmony_ci<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
1821cb0ef41Sopenharmony_ci<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
1831cb0ef41Sopenharmony_ci<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
1841cb0ef41Sopenharmony_ci<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
1851cb0ef41Sopenharmony_ci<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
1861cb0ef41Sopenharmony_ci<li><a href="console.html" class="nav-console">Console</a></li>
1871cb0ef41Sopenharmony_ci<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
1881cb0ef41Sopenharmony_ci<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
1891cb0ef41Sopenharmony_ci<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
1901cb0ef41Sopenharmony_ci<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
1911cb0ef41Sopenharmony_ci<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
1921cb0ef41Sopenharmony_ci<li><a href="dns.html" class="nav-dns">DNS</a></li>
1931cb0ef41Sopenharmony_ci<li><a href="domain.html" class="nav-domain">Domain</a></li>
1941cb0ef41Sopenharmony_ci<li><a href="errors.html" class="nav-errors">Errors</a></li>
1951cb0ef41Sopenharmony_ci<li><a href="events.html" class="nav-events">Events</a></li>
1961cb0ef41Sopenharmony_ci<li><a href="fs.html" class="nav-fs">File system</a></li>
1971cb0ef41Sopenharmony_ci<li><a href="globals.html" class="nav-globals">Globals</a></li>
1981cb0ef41Sopenharmony_ci<li><a href="http.html" class="nav-http">HTTP</a></li>
1991cb0ef41Sopenharmony_ci<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
2001cb0ef41Sopenharmony_ci<li><a href="https.html" class="nav-https">HTTPS</a></li>
2011cb0ef41Sopenharmony_ci<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
2021cb0ef41Sopenharmony_ci<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
2031cb0ef41Sopenharmony_ci<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
2041cb0ef41Sopenharmony_ci<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
2051cb0ef41Sopenharmony_ci<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
2061cb0ef41Sopenharmony_ci<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
2071cb0ef41Sopenharmony_ci<li><a href="net.html" class="nav-net">Net</a></li>
2081cb0ef41Sopenharmony_ci<li><a href="os.html" class="nav-os">OS</a></li>
2091cb0ef41Sopenharmony_ci<li><a href="path.html" class="nav-path">Path</a></li>
2101cb0ef41Sopenharmony_ci<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
2111cb0ef41Sopenharmony_ci<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
2121cb0ef41Sopenharmony_ci<li><a href="process.html" class="nav-process">Process</a></li>
2131cb0ef41Sopenharmony_ci<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
2141cb0ef41Sopenharmony_ci<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
2151cb0ef41Sopenharmony_ci<li><a href="readline.html" class="nav-readline">Readline</a></li>
2161cb0ef41Sopenharmony_ci<li><a href="repl.html" class="nav-repl">REPL</a></li>
2171cb0ef41Sopenharmony_ci<li><a href="report.html" class="nav-report">Report</a></li>
2181cb0ef41Sopenharmony_ci<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
2191cb0ef41Sopenharmony_ci<li><a href="stream.html" class="nav-stream">Stream</a></li>
2201cb0ef41Sopenharmony_ci<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
2211cb0ef41Sopenharmony_ci<li><a href="test.html" class="nav-test">Test runner</a></li>
2221cb0ef41Sopenharmony_ci<li><a href="timers.html" class="nav-timers">Timers</a></li>
2231cb0ef41Sopenharmony_ci<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
2241cb0ef41Sopenharmony_ci<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
2251cb0ef41Sopenharmony_ci<li><a href="tty.html" class="nav-tty">TTY</a></li>
2261cb0ef41Sopenharmony_ci<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
2271cb0ef41Sopenharmony_ci<li><a href="url.html" class="nav-url">URL</a></li>
2281cb0ef41Sopenharmony_ci<li><a href="util.html" class="nav-util">Utilities</a></li>
2291cb0ef41Sopenharmony_ci<li><a href="v8.html" class="nav-v8">V8</a></li>
2301cb0ef41Sopenharmony_ci<li><a href="vm.html" class="nav-vm">VM</a></li>
2311cb0ef41Sopenharmony_ci<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
2321cb0ef41Sopenharmony_ci<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
2331cb0ef41Sopenharmony_ci<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
2341cb0ef41Sopenharmony_ci<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
2351cb0ef41Sopenharmony_ci<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
2361cb0ef41Sopenharmony_ci</ul>
2371cb0ef41Sopenharmony_ci<hr class="line">
2381cb0ef41Sopenharmony_ci<ul>
2391cb0ef41Sopenharmony_ci<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
2401cb0ef41Sopenharmony_ci</ul></div>
2411cb0ef41Sopenharmony_ci    </li>
2421cb0ef41Sopenharmony_ci  
2431cb0ef41Sopenharmony_ci            
2441cb0ef41Sopenharmony_ci    <li class="picker-header">
2451cb0ef41Sopenharmony_ci      <a href="#">
2461cb0ef41Sopenharmony_ci        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
2471cb0ef41Sopenharmony_ci        Other versions
2481cb0ef41Sopenharmony_ci      </a>
2491cb0ef41Sopenharmony_ci      <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v21.x/api/async_context.html">21.x</a></li>
2501cb0ef41Sopenharmony_ci<li><a href="https://nodejs.org/docs/latest-v20.x/api/async_context.html">20.x <b>LTS</b></a></li>
2511cb0ef41Sopenharmony_ci<li><a href="https://nodejs.org/docs/latest-v19.x/api/async_context.html">19.x</a></li>
2521cb0ef41Sopenharmony_ci<li><a href="https://nodejs.org/docs/latest-v18.x/api/async_context.html">18.x <b>LTS</b></a></li>
2531cb0ef41Sopenharmony_ci<li><a href="https://nodejs.org/docs/latest-v17.x/api/async_context.html">17.x</a></li>
2541cb0ef41Sopenharmony_ci<li><a href="https://nodejs.org/docs/latest-v16.x/api/async_context.html">16.x</a></li></ol></div>
2551cb0ef41Sopenharmony_ci    </li>
2561cb0ef41Sopenharmony_ci  
2571cb0ef41Sopenharmony_ci            <li class="picker-header">
2581cb0ef41Sopenharmony_ci              <a href="#">
2591cb0ef41Sopenharmony_ci                <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
2601cb0ef41Sopenharmony_ci                Options
2611cb0ef41Sopenharmony_ci              </a>
2621cb0ef41Sopenharmony_ci        
2631cb0ef41Sopenharmony_ci              <div class="picker">
2641cb0ef41Sopenharmony_ci                <ul>
2651cb0ef41Sopenharmony_ci                  <li>
2661cb0ef41Sopenharmony_ci                    <a href="all.html">View on single page</a>
2671cb0ef41Sopenharmony_ci                  </li>
2681cb0ef41Sopenharmony_ci                  <li>
2691cb0ef41Sopenharmony_ci                    <a href="async_context.json">View as JSON</a>
2701cb0ef41Sopenharmony_ci                  </li>
2711cb0ef41Sopenharmony_ci                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/async_context.md">Edit on GitHub</a></li>    
2721cb0ef41Sopenharmony_ci                </ul>
2731cb0ef41Sopenharmony_ci              </div>
2741cb0ef41Sopenharmony_ci            </li>
2751cb0ef41Sopenharmony_ci          </ul>
2761cb0ef41Sopenharmony_ci        </div>
2771cb0ef41Sopenharmony_ci        <hr>
2781cb0ef41Sopenharmony_ci      </header>
2791cb0ef41Sopenharmony_ci
2801cb0ef41Sopenharmony_ci      <details id="toc" open><summary>Table of contents</summary><ul>
2811cb0ef41Sopenharmony_ci<li><span class="stability_2"><a href="#asynchronous-context-tracking">Asynchronous context tracking</a></span>
2821cb0ef41Sopenharmony_ci<ul>
2831cb0ef41Sopenharmony_ci<li><a href="#introduction">Introduction</a></li>
2841cb0ef41Sopenharmony_ci<li><a href="#class-asynclocalstorage">Class: <code>AsyncLocalStorage</code></a>
2851cb0ef41Sopenharmony_ci<ul>
2861cb0ef41Sopenharmony_ci<li><a href="#new-asynclocalstorage"><code>new AsyncLocalStorage()</code></a></li>
2871cb0ef41Sopenharmony_ci<li><span class="stability_1"><a href="#static-method-asynclocalstoragebindfn">Static method: <code>AsyncLocalStorage.bind(fn)</code></a></span></li>
2881cb0ef41Sopenharmony_ci<li><span class="stability_1"><a href="#static-method-asynclocalstoragesnapshot">Static method: <code>AsyncLocalStorage.snapshot()</code></a></span></li>
2891cb0ef41Sopenharmony_ci<li><span class="stability_1"><a href="#asynclocalstoragedisable"><code>asyncLocalStorage.disable()</code></a></span></li>
2901cb0ef41Sopenharmony_ci<li><a href="#asynclocalstoragegetstore"><code>asyncLocalStorage.getStore()</code></a></li>
2911cb0ef41Sopenharmony_ci<li><span class="stability_1"><a href="#asynclocalstorageenterwithstore"><code>asyncLocalStorage.enterWith(store)</code></a></span></li>
2921cb0ef41Sopenharmony_ci<li><a href="#asynclocalstoragerunstore-callback-args"><code>asyncLocalStorage.run(store, callback[, ...args])</code></a></li>
2931cb0ef41Sopenharmony_ci<li><span class="stability_1"><a href="#asynclocalstorageexitcallback-args"><code>asyncLocalStorage.exit(callback[, ...args])</code></a></span></li>
2941cb0ef41Sopenharmony_ci<li><a href="#usage-with-asyncawait">Usage with <code>async/await</code></a></li>
2951cb0ef41Sopenharmony_ci<li><a href="#troubleshooting-context-loss">Troubleshooting: Context loss</a></li>
2961cb0ef41Sopenharmony_ci</ul>
2971cb0ef41Sopenharmony_ci</li>
2981cb0ef41Sopenharmony_ci<li><a href="#class-asyncresource">Class: <code>AsyncResource</code></a>
2991cb0ef41Sopenharmony_ci<ul>
3001cb0ef41Sopenharmony_ci<li><a href="#new-asyncresourcetype-options"><code>new AsyncResource(type[, options])</code></a></li>
3011cb0ef41Sopenharmony_ci<li><a href="#static-method-asyncresourcebindfn-type-thisarg">Static method: <code>AsyncResource.bind(fn[, type[, thisArg]])</code></a></li>
3021cb0ef41Sopenharmony_ci<li><a href="#asyncresourcebindfn-thisarg"><code>asyncResource.bind(fn[, thisArg])</code></a></li>
3031cb0ef41Sopenharmony_ci<li><a href="#asyncresourceruninasyncscopefn-thisarg-args"><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code></a></li>
3041cb0ef41Sopenharmony_ci<li><a href="#asyncresourceemitdestroy"><code>asyncResource.emitDestroy()</code></a></li>
3051cb0ef41Sopenharmony_ci<li><a href="#asyncresourceasyncid"><code>asyncResource.asyncId()</code></a></li>
3061cb0ef41Sopenharmony_ci<li><a href="#asyncresourcetriggerasyncid"><code>asyncResource.triggerAsyncId()</code></a></li>
3071cb0ef41Sopenharmony_ci<li><a href="#using-asyncresource-for-a-worker-thread-pool">Using <code>AsyncResource</code> for a <code>Worker</code> thread pool</a></li>
3081cb0ef41Sopenharmony_ci<li><a href="#integrating-asyncresource-with-eventemitter">Integrating <code>AsyncResource</code> with <code>EventEmitter</code></a></li>
3091cb0ef41Sopenharmony_ci</ul>
3101cb0ef41Sopenharmony_ci</li>
3111cb0ef41Sopenharmony_ci</ul>
3121cb0ef41Sopenharmony_ci</li>
3131cb0ef41Sopenharmony_ci</ul></details>
3141cb0ef41Sopenharmony_ci
3151cb0ef41Sopenharmony_ci      <div id="apicontent">
3161cb0ef41Sopenharmony_ci        <h2>Asynchronous context tracking<span><a class="mark" href="#asynchronous-context-tracking" id="asynchronous-context-tracking">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynchronous_context_tracking"></a></h2>
3171cb0ef41Sopenharmony_ci
3181cb0ef41Sopenharmony_ci<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p>
3191cb0ef41Sopenharmony_ci<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>
3201cb0ef41Sopenharmony_ci<section><h3>Introduction<span><a class="mark" href="#introduction" id="introduction">#</a></span><a aria-hidden="true" class="legacy" id="async_context_introduction"></a></h3>
3211cb0ef41Sopenharmony_ci<p>These classes are used to associate state and propagate it throughout
3221cb0ef41Sopenharmony_cicallbacks and promise chains.
3231cb0ef41Sopenharmony_ciThey allow storing data throughout the lifetime of a web request
3241cb0ef41Sopenharmony_cior any other asynchronous duration. It is similar to thread-local storage
3251cb0ef41Sopenharmony_ciin other languages.</p>
3261cb0ef41Sopenharmony_ci<p>The <code>AsyncLocalStorage</code> and <code>AsyncResource</code> classes are part of the
3271cb0ef41Sopenharmony_ci<code>node:async_hooks</code> module:</p>
3281cb0ef41Sopenharmony_ci
3291cb0ef41Sopenharmony_ci<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> { <span class="hljs-title class_">AsyncLocalStorage</span>, <span class="hljs-title class_">AsyncResource</span> } <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> { <span class="hljs-title class_">AsyncLocalStorage</span>, <span class="hljs-title class_">AsyncResource</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);</code><button class="copy-button">copy</button></pre>
3301cb0ef41Sopenharmony_ci</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_context_class_asynclocalstorage"></a></h3>
3311cb0ef41Sopenharmony_ci<div class="api_metadata">
3321cb0ef41Sopenharmony_ci<details class="changelog"><summary>History</summary>
3331cb0ef41Sopenharmony_ci<table>
3341cb0ef41Sopenharmony_ci<tbody><tr><th>Version</th><th>Changes</th></tr>
3351cb0ef41Sopenharmony_ci<tr><td>v16.4.0</td>
3361cb0ef41Sopenharmony_ci<td><p>AsyncLocalStorage is now Stable. Previously, it had been Experimental.</p></td></tr>
3371cb0ef41Sopenharmony_ci<tr><td>v13.10.0, v12.17.0</td>
3381cb0ef41Sopenharmony_ci<td><p><span>Added in: v13.10.0, v12.17.0</span></p></td></tr>
3391cb0ef41Sopenharmony_ci</tbody></table>
3401cb0ef41Sopenharmony_ci</details>
3411cb0ef41Sopenharmony_ci</div>
3421cb0ef41Sopenharmony_ci<p>This class creates stores that stay coherent through asynchronous operations.</p>
3431cb0ef41Sopenharmony_ci<p>While you can create your own implementation on top of the <code>node:async_hooks</code>
3441cb0ef41Sopenharmony_cimodule, <code>AsyncLocalStorage</code> should be preferred as it is a performant and memory
3451cb0ef41Sopenharmony_cisafe implementation that involves significant optimizations that are non-obvious
3461cb0ef41Sopenharmony_cito implement.</p>
3471cb0ef41Sopenharmony_ci<p>The following example uses <code>AsyncLocalStorage</code> to build a simple logger
3481cb0ef41Sopenharmony_cithat assigns IDs to incoming HTTP requests and includes them in messages
3491cb0ef41Sopenharmony_cilogged within each request.</p>
3501cb0ef41Sopenharmony_ci
3511cb0ef41Sopenharmony_ci<pre class="with-58-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> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
3521cb0ef41Sopenharmony_ci<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
3531cb0ef41Sopenharmony_ci
3541cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
3551cb0ef41Sopenharmony_ci
3561cb0ef41Sopenharmony_ci<span class="hljs-keyword">function</span> <span class="hljs-title function_">logWithId</span>(<span class="hljs-params">msg</span>) {
3571cb0ef41Sopenharmony_ci  <span class="hljs-keyword">const</span> id = asyncLocalStorage.<span class="hljs-title function_">getStore</span>();
3581cb0ef41Sopenharmony_ci  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${id !== <span class="hljs-literal">undefined</span> ? id : <span class="hljs-string">'-'</span>}</span>:`</span>, msg);
3591cb0ef41Sopenharmony_ci}
3601cb0ef41Sopenharmony_ci
3611cb0ef41Sopenharmony_ci<span class="hljs-keyword">let</span> idSeq = <span class="hljs-number">0</span>;
3621cb0ef41Sopenharmony_cihttp.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
3631cb0ef41Sopenharmony_ci  asyncLocalStorage.<span class="hljs-title function_">run</span>(idSeq++, <span class="hljs-function">() =></span> {
3641cb0ef41Sopenharmony_ci    <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'start'</span>);
3651cb0ef41Sopenharmony_ci    <span class="hljs-comment">// Imagine any chain of async operations here</span>
3661cb0ef41Sopenharmony_ci    <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
3671cb0ef41Sopenharmony_ci      <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'finish'</span>);
3681cb0ef41Sopenharmony_ci      res.<span class="hljs-title function_">end</span>();
3691cb0ef41Sopenharmony_ci    });
3701cb0ef41Sopenharmony_ci  });
3711cb0ef41Sopenharmony_ci}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);
3721cb0ef41Sopenharmony_ci
3731cb0ef41Sopenharmony_cihttp.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
3741cb0ef41Sopenharmony_cihttp.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
3751cb0ef41Sopenharmony_ci<span class="hljs-comment">// Prints:</span>
3761cb0ef41Sopenharmony_ci<span class="hljs-comment">//   0: start</span>
3771cb0ef41Sopenharmony_ci<span class="hljs-comment">//   1: start</span>
3781cb0ef41Sopenharmony_ci<span class="hljs-comment">//   0: finish</span>
3791cb0ef41Sopenharmony_ci<span class="hljs-comment">//   1: finish</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
3801cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
3811cb0ef41Sopenharmony_ci
3821cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
3831cb0ef41Sopenharmony_ci
3841cb0ef41Sopenharmony_ci<span class="hljs-keyword">function</span> <span class="hljs-title function_">logWithId</span>(<span class="hljs-params">msg</span>) {
3851cb0ef41Sopenharmony_ci  <span class="hljs-keyword">const</span> id = asyncLocalStorage.<span class="hljs-title function_">getStore</span>();
3861cb0ef41Sopenharmony_ci  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${id !== <span class="hljs-literal">undefined</span> ? id : <span class="hljs-string">'-'</span>}</span>:`</span>, msg);
3871cb0ef41Sopenharmony_ci}
3881cb0ef41Sopenharmony_ci
3891cb0ef41Sopenharmony_ci<span class="hljs-keyword">let</span> idSeq = <span class="hljs-number">0</span>;
3901cb0ef41Sopenharmony_cihttp.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
3911cb0ef41Sopenharmony_ci  asyncLocalStorage.<span class="hljs-title function_">run</span>(idSeq++, <span class="hljs-function">() =></span> {
3921cb0ef41Sopenharmony_ci    <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'start'</span>);
3931cb0ef41Sopenharmony_ci    <span class="hljs-comment">// Imagine any chain of async operations here</span>
3941cb0ef41Sopenharmony_ci    <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
3951cb0ef41Sopenharmony_ci      <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'finish'</span>);
3961cb0ef41Sopenharmony_ci      res.<span class="hljs-title function_">end</span>();
3971cb0ef41Sopenharmony_ci    });
3981cb0ef41Sopenharmony_ci  });
3991cb0ef41Sopenharmony_ci}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);
4001cb0ef41Sopenharmony_ci
4011cb0ef41Sopenharmony_cihttp.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
4021cb0ef41Sopenharmony_cihttp.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
4031cb0ef41Sopenharmony_ci<span class="hljs-comment">// Prints:</span>
4041cb0ef41Sopenharmony_ci<span class="hljs-comment">//   0: start</span>
4051cb0ef41Sopenharmony_ci<span class="hljs-comment">//   1: start</span>
4061cb0ef41Sopenharmony_ci<span class="hljs-comment">//   0: finish</span>
4071cb0ef41Sopenharmony_ci<span class="hljs-comment">//   1: finish</span></code><button class="copy-button">copy</button></pre>
4081cb0ef41Sopenharmony_ci<p>Each instance of <code>AsyncLocalStorage</code> maintains an independent storage context.
4091cb0ef41Sopenharmony_ciMultiple instances can safely exist simultaneously without risk of interfering
4101cb0ef41Sopenharmony_ciwith each other's data.</p>
4111cb0ef41Sopenharmony_ci<h4><code>new AsyncLocalStorage()</code><span><a class="mark" href="#new-asynclocalstorage" id="new-asynclocalstorage">#</a></span><a aria-hidden="true" class="legacy" id="async_context_new_asynclocalstorage"></a></h4>
4121cb0ef41Sopenharmony_ci<div class="api_metadata">
4131cb0ef41Sopenharmony_ci<details class="changelog"><summary>History</summary>
4141cb0ef41Sopenharmony_ci<table>
4151cb0ef41Sopenharmony_ci<tbody><tr><th>Version</th><th>Changes</th></tr>
4161cb0ef41Sopenharmony_ci<tr><td>v18.16.0</td>
4171cb0ef41Sopenharmony_ci<td><p>Removed experimental onPropagate option.</p></td></tr>
4181cb0ef41Sopenharmony_ci<tr><td>v18.13.0</td>
4191cb0ef41Sopenharmony_ci<td><p>Add option onPropagate.</p></td></tr>
4201cb0ef41Sopenharmony_ci<tr><td>v13.10.0, v12.17.0</td>
4211cb0ef41Sopenharmony_ci<td><p><span>Added in: v13.10.0, v12.17.0</span></p></td></tr>
4221cb0ef41Sopenharmony_ci</tbody></table>
4231cb0ef41Sopenharmony_ci</details>
4241cb0ef41Sopenharmony_ci</div>
4251cb0ef41Sopenharmony_ci<p>Creates a new instance of <code>AsyncLocalStorage</code>. Store is only provided within a
4261cb0ef41Sopenharmony_ci<code>run()</code> call or after an <code>enterWith()</code> call.</p>
4271cb0ef41Sopenharmony_ci<h4>Static method: <code>AsyncLocalStorage.bind(fn)</code><span><a class="mark" href="#static-method-asynclocalstoragebindfn" id="static-method-asynclocalstoragebindfn">#</a></span><a aria-hidden="true" class="legacy" id="async_context_static_method_asynclocalstorage_bind_fn"></a></h4>
4281cb0ef41Sopenharmony_ci<div class="api_metadata">
4291cb0ef41Sopenharmony_ci<span>Added in: v18.16.0</span>
4301cb0ef41Sopenharmony_ci</div>
4311cb0ef41Sopenharmony_ci<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
4321cb0ef41Sopenharmony_ci<ul>
4331cb0ef41Sopenharmony_ci<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to bind to the current execution context.</li>
4341cb0ef41Sopenharmony_ci<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A new function that calls <code>fn</code> within the captured
4351cb0ef41Sopenharmony_ciexecution context.</li>
4361cb0ef41Sopenharmony_ci</ul>
4371cb0ef41Sopenharmony_ci<p>Binds the given function to the current execution context.</p>
4381cb0ef41Sopenharmony_ci<h4>Static method: <code>AsyncLocalStorage.snapshot()</code><span><a class="mark" href="#static-method-asynclocalstoragesnapshot" id="static-method-asynclocalstoragesnapshot">#</a></span><a aria-hidden="true" class="legacy" id="async_context_static_method_asynclocalstorage_snapshot"></a></h4>
4391cb0ef41Sopenharmony_ci<div class="api_metadata">
4401cb0ef41Sopenharmony_ci<span>Added in: v18.16.0</span>
4411cb0ef41Sopenharmony_ci</div>
4421cb0ef41Sopenharmony_ci<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
4431cb0ef41Sopenharmony_ci<ul>
4441cb0ef41Sopenharmony_ci<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A new function with the signature
4451cb0ef41Sopenharmony_ci<code>(fn: (...args) : R, ...args) : R</code>.</li>
4461cb0ef41Sopenharmony_ci</ul>
4471cb0ef41Sopenharmony_ci<p>Captures the current execution context and returns a function that accepts a
4481cb0ef41Sopenharmony_cifunction as an argument. Whenever the returned function is called, it
4491cb0ef41Sopenharmony_cicalls the function passed to it within the captured context.</p>
4501cb0ef41Sopenharmony_ci<pre><code class="language-js"><span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
4511cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> runInAsyncScope = asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">123</span>, <span class="hljs-function">() =></span> <span class="hljs-title class_">AsyncLocalStorage</span>.<span class="hljs-title function_">snapshot</span>());
4521cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> result = asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">321</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-function">() =></span> asyncLocalStorage.<span class="hljs-title function_">getStore</span>()));
4531cb0ef41Sopenharmony_ci<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);  <span class="hljs-comment">// returns 123</span></code> <button class="copy-button">copy</button></pre>
4541cb0ef41Sopenharmony_ci<p>AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
4551cb0ef41Sopenharmony_ciasync context tracking purposes, for example:</p>
4561cb0ef41Sopenharmony_ci<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
4571cb0ef41Sopenharmony_ci  #runInAsyncScope = <span class="hljs-title class_">AsyncLocalStorage</span>.<span class="hljs-title function_">snapshot</span>();
4581cb0ef41Sopenharmony_ci
4591cb0ef41Sopenharmony_ci  <span class="hljs-title function_">get</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.#<span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-function">() =></span> asyncLocalStorage.<span class="hljs-title function_">getStore</span>()); }
4601cb0ef41Sopenharmony_ci}
4611cb0ef41Sopenharmony_ci
4621cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> foo = asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">123</span>, <span class="hljs-function">() =></span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>());
4631cb0ef41Sopenharmony_ci<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">321</span>, <span class="hljs-function">() =></span> foo.<span class="hljs-title function_">get</span>())); <span class="hljs-comment">// returns 123</span></code> <button class="copy-button">copy</button></pre>
4641cb0ef41Sopenharmony_ci<h4><code>asyncLocalStorage.disable()</code><span><a class="mark" href="#asynclocalstoragedisable" id="asynclocalstoragedisable">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_disable"></a></h4>
4651cb0ef41Sopenharmony_ci<div class="api_metadata">
4661cb0ef41Sopenharmony_ci<span>Added in: v13.10.0, v12.17.0</span>
4671cb0ef41Sopenharmony_ci</div>
4681cb0ef41Sopenharmony_ci<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
4691cb0ef41Sopenharmony_ci<p>Disables the instance of <code>AsyncLocalStorage</code>. All subsequent calls
4701cb0ef41Sopenharmony_cito <code>asyncLocalStorage.getStore()</code> will return <code>undefined</code> until
4711cb0ef41Sopenharmony_ci<code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code> is called again.</p>
4721cb0ef41Sopenharmony_ci<p>When calling <code>asyncLocalStorage.disable()</code>, all current contexts linked to the
4731cb0ef41Sopenharmony_ciinstance will be exited.</p>
4741cb0ef41Sopenharmony_ci<p>Calling <code>asyncLocalStorage.disable()</code> is required before the
4751cb0ef41Sopenharmony_ci<code>asyncLocalStorage</code> can be garbage collected. This does not apply to stores
4761cb0ef41Sopenharmony_ciprovided by the <code>asyncLocalStorage</code>, as those objects are garbage collected
4771cb0ef41Sopenharmony_cialong with the corresponding async resources.</p>
4781cb0ef41Sopenharmony_ci<p>Use this method when the <code>asyncLocalStorage</code> is not in use anymore
4791cb0ef41Sopenharmony_ciin the current process.</p>
4801cb0ef41Sopenharmony_ci<h4><code>asyncLocalStorage.getStore()</code><span><a class="mark" href="#asynclocalstoragegetstore" id="asynclocalstoragegetstore">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_getstore"></a></h4>
4811cb0ef41Sopenharmony_ci<div class="api_metadata">
4821cb0ef41Sopenharmony_ci<span>Added in: v13.10.0, v12.17.0</span>
4831cb0ef41Sopenharmony_ci</div>
4841cb0ef41Sopenharmony_ci<ul>
4851cb0ef41Sopenharmony_ci<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
4861cb0ef41Sopenharmony_ci</ul>
4871cb0ef41Sopenharmony_ci<p>Returns the current store.
4881cb0ef41Sopenharmony_ciIf called outside of an asynchronous context initialized by
4891cb0ef41Sopenharmony_cicalling <code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code>, it
4901cb0ef41Sopenharmony_cireturns <code>undefined</code>.</p>
4911cb0ef41Sopenharmony_ci<h4><code>asyncLocalStorage.enterWith(store)</code><span><a class="mark" href="#asynclocalstorageenterwithstore" id="asynclocalstorageenterwithstore">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_enterwith_store"></a></h4>
4921cb0ef41Sopenharmony_ci<div class="api_metadata">
4931cb0ef41Sopenharmony_ci<span>Added in: v13.11.0, v12.17.0</span>
4941cb0ef41Sopenharmony_ci</div>
4951cb0ef41Sopenharmony_ci<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
4961cb0ef41Sopenharmony_ci<ul>
4971cb0ef41Sopenharmony_ci<li><code>store</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
4981cb0ef41Sopenharmony_ci</ul>
4991cb0ef41Sopenharmony_ci<p>Transitions into the context for the remainder of the current
5001cb0ef41Sopenharmony_cisynchronous execution and then persists the store through any following
5011cb0ef41Sopenharmony_ciasynchronous calls.</p>
5021cb0ef41Sopenharmony_ci<p>Example:</p>
5031cb0ef41Sopenharmony_ci<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
5041cb0ef41Sopenharmony_ci<span class="hljs-comment">// Replaces previous store with the given store object</span>
5051cb0ef41Sopenharmony_ciasyncLocalStorage.<span class="hljs-title function_">enterWith</span>(store);
5061cb0ef41Sopenharmony_ciasyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
5071cb0ef41Sopenharmony_ci<span class="hljs-title function_">someAsyncOperation</span>(<span class="hljs-function">() =></span> {
5081cb0ef41Sopenharmony_ci  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span>
5091cb0ef41Sopenharmony_ci});</code> <button class="copy-button">copy</button></pre>
5101cb0ef41Sopenharmony_ci<p>This transition will continue for the <em>entire</em> synchronous execution.
5111cb0ef41Sopenharmony_ciThis means that if, for example, the context is entered within an event
5121cb0ef41Sopenharmony_cihandler subsequent event handlers will also run within that context unless
5131cb0ef41Sopenharmony_cispecifically bound to another context with an <code>AsyncResource</code>. That is why
5141cb0ef41Sopenharmony_ci<code>run()</code> should be preferred over <code>enterWith()</code> unless there are strong reasons
5151cb0ef41Sopenharmony_cito use the latter method.</p>
5161cb0ef41Sopenharmony_ci<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
5171cb0ef41Sopenharmony_ci
5181cb0ef41Sopenharmony_ciemitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'my-event'</span>, <span class="hljs-function">() =></span> {
5191cb0ef41Sopenharmony_ci  asyncLocalStorage.<span class="hljs-title function_">enterWith</span>(store);
5201cb0ef41Sopenharmony_ci});
5211cb0ef41Sopenharmony_ciemitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'my-event'</span>, <span class="hljs-function">() =></span> {
5221cb0ef41Sopenharmony_ci  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span>
5231cb0ef41Sopenharmony_ci});
5241cb0ef41Sopenharmony_ci
5251cb0ef41Sopenharmony_ciasyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
5261cb0ef41Sopenharmony_ciemitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'my-event'</span>);
5271cb0ef41Sopenharmony_ciasyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span></code> <button class="copy-button">copy</button></pre>
5281cb0ef41Sopenharmony_ci<h4><code>asyncLocalStorage.run(store, callback[, ...args])</code><span><a class="mark" href="#asynclocalstoragerunstore-callback-args" id="asynclocalstoragerunstore-callback-args">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_run_store_callback_args"></a></h4>
5291cb0ef41Sopenharmony_ci<div class="api_metadata">
5301cb0ef41Sopenharmony_ci<span>Added in: v13.10.0, v12.17.0</span>
5311cb0ef41Sopenharmony_ci</div>
5321cb0ef41Sopenharmony_ci<ul>
5331cb0ef41Sopenharmony_ci<li><code>store</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
5341cb0ef41Sopenharmony_ci<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
5351cb0ef41Sopenharmony_ci<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
5361cb0ef41Sopenharmony_ci</ul>
5371cb0ef41Sopenharmony_ci<p>Runs a function synchronously within a context and returns its
5381cb0ef41Sopenharmony_cireturn value. The store is not accessible outside of the callback function.
5391cb0ef41Sopenharmony_ciThe store is accessible to any asynchronous operations created within the
5401cb0ef41Sopenharmony_cicallback.</p>
5411cb0ef41Sopenharmony_ci<p>The optional <code>args</code> are passed to the callback function.</p>
5421cb0ef41Sopenharmony_ci<p>If the callback function throws an error, the error is thrown by <code>run()</code> too.
5431cb0ef41Sopenharmony_ciThe stacktrace is not impacted by this call and the context is exited.</p>
5441cb0ef41Sopenharmony_ci<p>Example:</p>
5451cb0ef41Sopenharmony_ci<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span> };
5461cb0ef41Sopenharmony_ci<span class="hljs-keyword">try</span> {
5471cb0ef41Sopenharmony_ci  asyncLocalStorage.<span class="hljs-title function_">run</span>(store, <span class="hljs-function">() =></span> {
5481cb0ef41Sopenharmony_ci    asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
5491cb0ef41Sopenharmony_ci    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
5501cb0ef41Sopenharmony_ci      asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
5511cb0ef41Sopenharmony_ci    }, <span class="hljs-number">200</span>);
5521cb0ef41Sopenharmony_ci    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
5531cb0ef41Sopenharmony_ci  });
5541cb0ef41Sopenharmony_ci} <span class="hljs-keyword">catch</span> (e) {
5551cb0ef41Sopenharmony_ci  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
5561cb0ef41Sopenharmony_ci  <span class="hljs-comment">// The error will be caught here</span>
5571cb0ef41Sopenharmony_ci}</code> <button class="copy-button">copy</button></pre>
5581cb0ef41Sopenharmony_ci<h4><code>asyncLocalStorage.exit(callback[, ...args])</code><span><a class="mark" href="#asynclocalstorageexitcallback-args" id="asynclocalstorageexitcallback-args">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_exit_callback_args"></a></h4>
5591cb0ef41Sopenharmony_ci<div class="api_metadata">
5601cb0ef41Sopenharmony_ci<span>Added in: v13.10.0, v12.17.0</span>
5611cb0ef41Sopenharmony_ci</div>
5621cb0ef41Sopenharmony_ci<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
5631cb0ef41Sopenharmony_ci<ul>
5641cb0ef41Sopenharmony_ci<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
5651cb0ef41Sopenharmony_ci<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
5661cb0ef41Sopenharmony_ci</ul>
5671cb0ef41Sopenharmony_ci<p>Runs a function synchronously outside of a context and returns its
5681cb0ef41Sopenharmony_cireturn value. The store is not accessible within the callback function or
5691cb0ef41Sopenharmony_cithe asynchronous operations created within the callback. Any <code>getStore()</code>
5701cb0ef41Sopenharmony_cicall done within the callback function will always return <code>undefined</code>.</p>
5711cb0ef41Sopenharmony_ci<p>The optional <code>args</code> are passed to the callback function.</p>
5721cb0ef41Sopenharmony_ci<p>If the callback function throws an error, the error is thrown by <code>exit()</code> too.
5731cb0ef41Sopenharmony_ciThe stacktrace is not impacted by this call and the context is re-entered.</p>
5741cb0ef41Sopenharmony_ci<p>Example:</p>
5751cb0ef41Sopenharmony_ci<pre><code class="language-js"><span class="hljs-comment">// Within a call to run</span>
5761cb0ef41Sopenharmony_ci<span class="hljs-keyword">try</span> {
5771cb0ef41Sopenharmony_ci  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object or value</span>
5781cb0ef41Sopenharmony_ci  asyncLocalStorage.<span class="hljs-title function_">exit</span>(<span class="hljs-function">() =></span> {
5791cb0ef41Sopenharmony_ci    asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
5801cb0ef41Sopenharmony_ci    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
5811cb0ef41Sopenharmony_ci  });
5821cb0ef41Sopenharmony_ci} <span class="hljs-keyword">catch</span> (e) {
5831cb0ef41Sopenharmony_ci  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object or value</span>
5841cb0ef41Sopenharmony_ci  <span class="hljs-comment">// The error will be caught here</span>
5851cb0ef41Sopenharmony_ci}</code> <button class="copy-button">copy</button></pre>
5861cb0ef41Sopenharmony_ci<h4>Usage with <code>async/await</code><span><a class="mark" href="#usage-with-asyncawait" id="usage-with-asyncawait">#</a></span><a aria-hidden="true" class="legacy" id="async_context_usage_with_async_await"></a></h4>
5871cb0ef41Sopenharmony_ci<p>If, within an async function, only one <code>await</code> call is to run within a context,
5881cb0ef41Sopenharmony_cithe following pattern should be used:</p>
5891cb0ef41Sopenharmony_ci<pre><code class="language-js"><span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params"></span>) {
5901cb0ef41Sopenharmony_ci  <span class="hljs-keyword">await</span> asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>(), <span class="hljs-function">() =></span> {
5911cb0ef41Sopenharmony_ci    asyncLocalStorage.<span class="hljs-title function_">getStore</span>().<span class="hljs-title function_">set</span>(<span class="hljs-string">'key'</span>, value);
5921cb0ef41Sopenharmony_ci    <span class="hljs-keyword">return</span> <span class="hljs-title function_">foo</span>(); <span class="hljs-comment">// The return value of foo will be awaited</span>
5931cb0ef41Sopenharmony_ci  });
5941cb0ef41Sopenharmony_ci}</code> <button class="copy-button">copy</button></pre>
5951cb0ef41Sopenharmony_ci<p>In this example, the store is only available in the callback function and the
5961cb0ef41Sopenharmony_cifunctions called by <code>foo</code>. Outside of <code>run</code>, calling <code>getStore</code> will return
5971cb0ef41Sopenharmony_ci<code>undefined</code>.</p>
5981cb0ef41Sopenharmony_ci<h4>Troubleshooting: Context loss<span><a class="mark" href="#troubleshooting-context-loss" id="troubleshooting-context-loss">#</a></span><a aria-hidden="true" class="legacy" id="async_context_troubleshooting_context_loss"></a></h4>
5991cb0ef41Sopenharmony_ci<p>In most cases, <code>AsyncLocalStorage</code> works without issues. In rare situations, the
6001cb0ef41Sopenharmony_cicurrent store is lost in one of the asynchronous operations.</p>
6011cb0ef41Sopenharmony_ci<p>If your code is callback-based, it is enough to promisify it with
6021cb0ef41Sopenharmony_ci<a href="util.html#utilpromisifyoriginal"><code>util.promisify()</code></a> so it starts working with native promises.</p>
6031cb0ef41Sopenharmony_ci<p>If you need to use a callback-based API or your code assumes
6041cb0ef41Sopenharmony_cia custom thenable implementation, use the <a href="#class-asyncresource"><code>AsyncResource</code></a> class
6051cb0ef41Sopenharmony_cito associate the asynchronous operation with the correct execution context.
6061cb0ef41Sopenharmony_ciFind the function call responsible for the context loss by logging the content
6071cb0ef41Sopenharmony_ciof <code>asyncLocalStorage.getStore()</code> after the calls you suspect are responsible
6081cb0ef41Sopenharmony_cifor the loss. When the code logs <code>undefined</code>, the last callback called is
6091cb0ef41Sopenharmony_ciprobably responsible for the context loss.</p>
6101cb0ef41Sopenharmony_ci</section><section><h3>Class: <code>AsyncResource</code><span><a class="mark" href="#class-asyncresource" id="class-asyncresource">#</a></span><a aria-hidden="true" class="legacy" id="async_context_class_asyncresource"></a></h3>
6111cb0ef41Sopenharmony_ci<div class="api_metadata">
6121cb0ef41Sopenharmony_ci<details class="changelog"><summary>History</summary>
6131cb0ef41Sopenharmony_ci<table>
6141cb0ef41Sopenharmony_ci<tbody><tr><th>Version</th><th>Changes</th></tr>
6151cb0ef41Sopenharmony_ci<tr><td>v16.4.0</td>
6161cb0ef41Sopenharmony_ci<td><p>AsyncResource is now Stable. Previously, it had been Experimental.</p></td></tr>
6171cb0ef41Sopenharmony_ci</tbody></table>
6181cb0ef41Sopenharmony_ci</details>
6191cb0ef41Sopenharmony_ci</div>
6201cb0ef41Sopenharmony_ci<p>The class <code>AsyncResource</code> is designed to be extended by the embedder's async
6211cb0ef41Sopenharmony_ciresources. Using this, users can easily trigger the lifetime events of their
6221cb0ef41Sopenharmony_ciown resources.</p>
6231cb0ef41Sopenharmony_ci<p>The <code>init</code> hook will trigger when an <code>AsyncResource</code> is instantiated.</p>
6241cb0ef41Sopenharmony_ci<p>The following is an overview of the <code>AsyncResource</code> API.</p>
6251cb0ef41Sopenharmony_ci
6261cb0ef41Sopenharmony_ci<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> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
6271cb0ef41Sopenharmony_ci
6281cb0ef41Sopenharmony_ci<span class="hljs-comment">// AsyncResource() is meant to be extended. Instantiating a</span>
6291cb0ef41Sopenharmony_ci<span class="hljs-comment">// new AsyncResource() also triggers init. If triggerAsyncId is omitted then</span>
6301cb0ef41Sopenharmony_ci<span class="hljs-comment">// async_hook.executionAsyncId() is used.</span>
6311cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> asyncResource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncResource</span>(
6321cb0ef41Sopenharmony_ci  type, { <span class="hljs-attr">triggerAsyncId</span>: <span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-attr">requireManualDestroy</span>: <span class="hljs-literal">false</span> },
6331cb0ef41Sopenharmony_ci);
6341cb0ef41Sopenharmony_ci
6351cb0ef41Sopenharmony_ci<span class="hljs-comment">// Run a function in the execution context of the resource. This will</span>
6361cb0ef41Sopenharmony_ci<span class="hljs-comment">// * establish the context of the resource</span>
6371cb0ef41Sopenharmony_ci<span class="hljs-comment">// * trigger the AsyncHooks before callbacks</span>
6381cb0ef41Sopenharmony_ci<span class="hljs-comment">// * call the provided function `fn` with the supplied arguments</span>
6391cb0ef41Sopenharmony_ci<span class="hljs-comment">// * trigger the AsyncHooks after callbacks</span>
6401cb0ef41Sopenharmony_ci<span class="hljs-comment">// * restore the original execution context</span>
6411cb0ef41Sopenharmony_ciasyncResource.<span class="hljs-title function_">runInAsyncScope</span>(fn, thisArg, ...args);
6421cb0ef41Sopenharmony_ci
6431cb0ef41Sopenharmony_ci<span class="hljs-comment">// Call AsyncHooks destroy callbacks.</span>
6441cb0ef41Sopenharmony_ciasyncResource.<span class="hljs-title function_">emitDestroy</span>();
6451cb0ef41Sopenharmony_ci
6461cb0ef41Sopenharmony_ci<span class="hljs-comment">// Return the unique ID assigned to the AsyncResource instance.</span>
6471cb0ef41Sopenharmony_ciasyncResource.<span class="hljs-title function_">asyncId</span>();
6481cb0ef41Sopenharmony_ci
6491cb0ef41Sopenharmony_ci<span class="hljs-comment">// Return the trigger ID for the AsyncResource instance.</span>
6501cb0ef41Sopenharmony_ciasyncResource.<span class="hljs-title function_">triggerAsyncId</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
6511cb0ef41Sopenharmony_ci
6521cb0ef41Sopenharmony_ci<span class="hljs-comment">// AsyncResource() is meant to be extended. Instantiating a</span>
6531cb0ef41Sopenharmony_ci<span class="hljs-comment">// new AsyncResource() also triggers init. If triggerAsyncId is omitted then</span>
6541cb0ef41Sopenharmony_ci<span class="hljs-comment">// async_hook.executionAsyncId() is used.</span>
6551cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> asyncResource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncResource</span>(
6561cb0ef41Sopenharmony_ci  type, { <span class="hljs-attr">triggerAsyncId</span>: <span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-attr">requireManualDestroy</span>: <span class="hljs-literal">false</span> },
6571cb0ef41Sopenharmony_ci);
6581cb0ef41Sopenharmony_ci
6591cb0ef41Sopenharmony_ci<span class="hljs-comment">// Run a function in the execution context of the resource. This will</span>
6601cb0ef41Sopenharmony_ci<span class="hljs-comment">// * establish the context of the resource</span>
6611cb0ef41Sopenharmony_ci<span class="hljs-comment">// * trigger the AsyncHooks before callbacks</span>
6621cb0ef41Sopenharmony_ci<span class="hljs-comment">// * call the provided function `fn` with the supplied arguments</span>
6631cb0ef41Sopenharmony_ci<span class="hljs-comment">// * trigger the AsyncHooks after callbacks</span>
6641cb0ef41Sopenharmony_ci<span class="hljs-comment">// * restore the original execution context</span>
6651cb0ef41Sopenharmony_ciasyncResource.<span class="hljs-title function_">runInAsyncScope</span>(fn, thisArg, ...args);
6661cb0ef41Sopenharmony_ci
6671cb0ef41Sopenharmony_ci<span class="hljs-comment">// Call AsyncHooks destroy callbacks.</span>
6681cb0ef41Sopenharmony_ciasyncResource.<span class="hljs-title function_">emitDestroy</span>();
6691cb0ef41Sopenharmony_ci
6701cb0ef41Sopenharmony_ci<span class="hljs-comment">// Return the unique ID assigned to the AsyncResource instance.</span>
6711cb0ef41Sopenharmony_ciasyncResource.<span class="hljs-title function_">asyncId</span>();
6721cb0ef41Sopenharmony_ci
6731cb0ef41Sopenharmony_ci<span class="hljs-comment">// Return the trigger ID for the AsyncResource instance.</span>
6741cb0ef41Sopenharmony_ciasyncResource.<span class="hljs-title function_">triggerAsyncId</span>();</code><button class="copy-button">copy</button></pre>
6751cb0ef41Sopenharmony_ci<h4><code>new AsyncResource(type[, options])</code><span><a class="mark" href="#new-asyncresourcetype-options" id="new-asyncresourcetype-options">#</a></span><a aria-hidden="true" class="legacy" id="async_context_new_asyncresource_type_options"></a></h4>
6761cb0ef41Sopenharmony_ci<ul>
6771cb0ef41Sopenharmony_ci<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 async event.</li>
6781cb0ef41Sopenharmony_ci<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
6791cb0ef41Sopenharmony_ci<ul>
6801cb0ef41Sopenharmony_ci<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 ID of the execution context that created this
6811cb0ef41Sopenharmony_ciasync event. <strong>Default:</strong> <code>executionAsyncId()</code>.</li>
6821cb0ef41Sopenharmony_ci<li><code>requireManualDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to <code>true</code>, disables <code>emitDestroy</code>
6831cb0ef41Sopenharmony_ciwhen the object is garbage collected. This usually does not need to be set
6841cb0ef41Sopenharmony_ci(even if <code>emitDestroy</code> is called manually), unless the resource's <code>asyncId</code>
6851cb0ef41Sopenharmony_ciis retrieved and the sensitive API's <code>emitDestroy</code> is called with it.
6861cb0ef41Sopenharmony_ciWhen set to <code>false</code>, the <code>emitDestroy</code> call on garbage collection
6871cb0ef41Sopenharmony_ciwill only take place if there is at least one active <code>destroy</code> hook.
6881cb0ef41Sopenharmony_ci<strong>Default:</strong> <code>false</code>.</li>
6891cb0ef41Sopenharmony_ci</ul>
6901cb0ef41Sopenharmony_ci</li>
6911cb0ef41Sopenharmony_ci</ul>
6921cb0ef41Sopenharmony_ci<p>Example usage:</p>
6931cb0ef41Sopenharmony_ci<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">DBQuery</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
6941cb0ef41Sopenharmony_ci  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">db</span>) {
6951cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'DBQuery'</span>);
6961cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span> = db;
6971cb0ef41Sopenharmony_ci  }
6981cb0ef41Sopenharmony_ci
6991cb0ef41Sopenharmony_ci  <span class="hljs-title function_">getInfo</span>(<span class="hljs-params">query, callback</span>) {
7001cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span>.<span class="hljs-title function_">get</span>(query, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
7011cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(callback, <span class="hljs-literal">null</span>, err, data);
7021cb0ef41Sopenharmony_ci    });
7031cb0ef41Sopenharmony_ci  }
7041cb0ef41Sopenharmony_ci
7051cb0ef41Sopenharmony_ci  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
7061cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span> = <span class="hljs-literal">null</span>;
7071cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>();
7081cb0ef41Sopenharmony_ci  }
7091cb0ef41Sopenharmony_ci}</code> <button class="copy-button">copy</button></pre>
7101cb0ef41Sopenharmony_ci<h4>Static method: <code>AsyncResource.bind(fn[, type[, thisArg]])</code><span><a class="mark" href="#static-method-asyncresourcebindfn-type-thisarg" id="static-method-asyncresourcebindfn-type-thisarg">#</a></span><a aria-hidden="true" class="legacy" id="async_context_static_method_asyncresource_bind_fn_type_thisarg"></a></h4>
7111cb0ef41Sopenharmony_ci<div class="api_metadata">
7121cb0ef41Sopenharmony_ci<details class="changelog"><summary>History</summary>
7131cb0ef41Sopenharmony_ci<table>
7141cb0ef41Sopenharmony_ci<tbody><tr><th>Version</th><th>Changes</th></tr>
7151cb0ef41Sopenharmony_ci<tr><td>v17.8.0</td>
7161cb0ef41Sopenharmony_ci<td><p>Changed the default when <code>thisArg</code> is undefined to use <code>this</code> from the caller.</p></td></tr>
7171cb0ef41Sopenharmony_ci<tr><td>v16.0.0</td>
7181cb0ef41Sopenharmony_ci<td><p>Added optional thisArg.</p></td></tr>
7191cb0ef41Sopenharmony_ci<tr><td>v14.8.0, v12.19.0</td>
7201cb0ef41Sopenharmony_ci<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
7211cb0ef41Sopenharmony_ci</tbody></table>
7221cb0ef41Sopenharmony_ci</details>
7231cb0ef41Sopenharmony_ci</div>
7241cb0ef41Sopenharmony_ci<ul>
7251cb0ef41Sopenharmony_ci<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to bind to the current execution context.</li>
7261cb0ef41Sopenharmony_ci<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> An optional name to associate with the underlying
7271cb0ef41Sopenharmony_ci<code>AsyncResource</code>.</li>
7281cb0ef41Sopenharmony_ci<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
7291cb0ef41Sopenharmony_ci</ul>
7301cb0ef41Sopenharmony_ci<p>Binds the given function to the current execution context.</p>
7311cb0ef41Sopenharmony_ci<p>The returned function will have an <code>asyncResource</code> property referencing
7321cb0ef41Sopenharmony_cithe <code>AsyncResource</code> to which the function is bound.</p>
7331cb0ef41Sopenharmony_ci<h4><code>asyncResource.bind(fn[, thisArg])</code><span><a class="mark" href="#asyncresourcebindfn-thisarg" id="asyncresourcebindfn-thisarg">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_bind_fn_thisarg"></a></h4>
7341cb0ef41Sopenharmony_ci<div class="api_metadata">
7351cb0ef41Sopenharmony_ci<details class="changelog"><summary>History</summary>
7361cb0ef41Sopenharmony_ci<table>
7371cb0ef41Sopenharmony_ci<tbody><tr><th>Version</th><th>Changes</th></tr>
7381cb0ef41Sopenharmony_ci<tr><td>v17.8.0</td>
7391cb0ef41Sopenharmony_ci<td><p>Changed the default when <code>thisArg</code> is undefined to use <code>this</code> from the caller.</p></td></tr>
7401cb0ef41Sopenharmony_ci<tr><td>v16.0.0</td>
7411cb0ef41Sopenharmony_ci<td><p>Added optional thisArg.</p></td></tr>
7421cb0ef41Sopenharmony_ci<tr><td>v14.8.0, v12.19.0</td>
7431cb0ef41Sopenharmony_ci<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
7441cb0ef41Sopenharmony_ci</tbody></table>
7451cb0ef41Sopenharmony_ci</details>
7461cb0ef41Sopenharmony_ci</div>
7471cb0ef41Sopenharmony_ci<ul>
7481cb0ef41Sopenharmony_ci<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to bind to the current <code>AsyncResource</code>.</li>
7491cb0ef41Sopenharmony_ci<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
7501cb0ef41Sopenharmony_ci</ul>
7511cb0ef41Sopenharmony_ci<p>Binds the given function to execute to this <code>AsyncResource</code>'s scope.</p>
7521cb0ef41Sopenharmony_ci<p>The returned function will have an <code>asyncResource</code> property referencing
7531cb0ef41Sopenharmony_cithe <code>AsyncResource</code> to which the function is bound.</p>
7541cb0ef41Sopenharmony_ci<h4><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code><span><a class="mark" href="#asyncresourceruninasyncscopefn-thisarg-args" id="asyncresourceruninasyncscopefn-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_runinasyncscope_fn_thisarg_args"></a></h4>
7551cb0ef41Sopenharmony_ci<div class="api_metadata">
7561cb0ef41Sopenharmony_ci<span>Added in: v9.6.0</span>
7571cb0ef41Sopenharmony_ci</div>
7581cb0ef41Sopenharmony_ci<ul>
7591cb0ef41Sopenharmony_ci<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to call in the execution context of this async
7601cb0ef41Sopenharmony_ciresource.</li>
7611cb0ef41Sopenharmony_ci<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The receiver to be used for the function call.</li>
7621cb0ef41Sopenharmony_ci<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Optional arguments to pass to the function.</li>
7631cb0ef41Sopenharmony_ci</ul>
7641cb0ef41Sopenharmony_ci<p>Call the provided function with the provided arguments in the execution context
7651cb0ef41Sopenharmony_ciof the async resource. This will establish the context, trigger the AsyncHooks
7661cb0ef41Sopenharmony_cibefore callbacks, call the function, trigger the AsyncHooks after callbacks, and
7671cb0ef41Sopenharmony_cithen restore the original execution context.</p>
7681cb0ef41Sopenharmony_ci<h4><code>asyncResource.emitDestroy()</code><span><a class="mark" href="#asyncresourceemitdestroy" id="asyncresourceemitdestroy">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_emitdestroy"></a></h4>
7691cb0ef41Sopenharmony_ci<ul>
7701cb0ef41Sopenharmony_ci<li>Returns: <a href="async_hooks.html#class-asyncresource" class="type">&#x3C;AsyncResource></a> A reference to <code>asyncResource</code>.</li>
7711cb0ef41Sopenharmony_ci</ul>
7721cb0ef41Sopenharmony_ci<p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will
7731cb0ef41Sopenharmony_cibe thrown if it is called more than once. This <strong>must</strong> be manually called. If
7741cb0ef41Sopenharmony_cithe resource is left to be collected by the GC then the <code>destroy</code> hooks will
7751cb0ef41Sopenharmony_cinever be called.</p>
7761cb0ef41Sopenharmony_ci<h4><code>asyncResource.asyncId()</code><span><a class="mark" href="#asyncresourceasyncid" id="asyncresourceasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_asyncid"></a></h4>
7771cb0ef41Sopenharmony_ci<ul>
7781cb0ef41Sopenharmony_ci<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The unique <code>asyncId</code> assigned to the resource.</li>
7791cb0ef41Sopenharmony_ci</ul>
7801cb0ef41Sopenharmony_ci<h4><code>asyncResource.triggerAsyncId()</code><span><a class="mark" href="#asyncresourcetriggerasyncid" id="asyncresourcetriggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_triggerasyncid"></a></h4>
7811cb0ef41Sopenharmony_ci<ul>
7821cb0ef41Sopenharmony_ci<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The same <code>triggerAsyncId</code> that is passed to the
7831cb0ef41Sopenharmony_ci<code>AsyncResource</code> constructor.</li>
7841cb0ef41Sopenharmony_ci</ul>
7851cb0ef41Sopenharmony_ci<p><a id="async-resource-worker-pool"></a></p>
7861cb0ef41Sopenharmony_ci<h4>Using <code>AsyncResource</code> for a <code>Worker</code> thread pool<span><a class="mark" href="#using-asyncresource-for-a-worker-thread-pool" id="using-asyncresource-for-a-worker-thread-pool">#</a></span><a aria-hidden="true" class="legacy" id="async_context_using_asyncresource_for_a_worker_thread_pool"></a></h4>
7871cb0ef41Sopenharmony_ci<p>The following example shows how to use the <code>AsyncResource</code> class to properly
7881cb0ef41Sopenharmony_ciprovide async tracking for a <a href="worker_threads.html#class-worker"><code>Worker</code></a> pool. Other resource pools, such as
7891cb0ef41Sopenharmony_cidatabase connection pools, can follow a similar model.</p>
7901cb0ef41Sopenharmony_ci<p>Assuming that the task is adding two numbers, using a file named
7911cb0ef41Sopenharmony_ci<code>task_processor.js</code> with the following content:</p>
7921cb0ef41Sopenharmony_ci
7931cb0ef41Sopenharmony_ci<pre class="with-54-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> { parentPort } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
7941cb0ef41Sopenharmony_ciparentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">task</span>) =></span> {
7951cb0ef41Sopenharmony_ci  parentPort.<span class="hljs-title function_">postMessage</span>(task.<span class="hljs-property">a</span> + task.<span class="hljs-property">b</span>);
7961cb0ef41Sopenharmony_ci});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
7971cb0ef41Sopenharmony_ciparentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">task</span>) =></span> {
7981cb0ef41Sopenharmony_ci  parentPort.<span class="hljs-title function_">postMessage</span>(task.<span class="hljs-property">a</span> + task.<span class="hljs-property">b</span>);
7991cb0ef41Sopenharmony_ci});</code><button class="copy-button">copy</button></pre>
8001cb0ef41Sopenharmony_ci<p>a Worker pool around it could use the following structure:</p>
8011cb0ef41Sopenharmony_ci
8021cb0ef41Sopenharmony_ci<pre class="with-54-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> { <span class="hljs-title class_">AsyncResource</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
8031cb0ef41Sopenharmony_ci<span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
8041cb0ef41Sopenharmony_ci<span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
8051cb0ef41Sopenharmony_ci<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Worker</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
8061cb0ef41Sopenharmony_ci
8071cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> kTaskInfo = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kTaskInfo'</span>);
8081cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> kWorkerFreedEvent = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kWorkerFreedEvent'</span>);
8091cb0ef41Sopenharmony_ci
8101cb0ef41Sopenharmony_ci<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
8111cb0ef41Sopenharmony_ci  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">callback</span>) {
8121cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'WorkerPoolTaskInfo'</span>);
8131cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span> = callback;
8141cb0ef41Sopenharmony_ci  }
8151cb0ef41Sopenharmony_ci
8161cb0ef41Sopenharmony_ci  <span class="hljs-title function_">done</span>(<span class="hljs-params">err, result</span>) {
8171cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span>, <span class="hljs-literal">null</span>, err, result);
8181cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>();  <span class="hljs-comment">// `TaskInfo`s are used only once.</span>
8191cb0ef41Sopenharmony_ci  }
8201cb0ef41Sopenharmony_ci}
8211cb0ef41Sopenharmony_ci
8221cb0ef41Sopenharmony_ci<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPool</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
8231cb0ef41Sopenharmony_ci  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">numThreads</span>) {
8241cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">super</span>();
8251cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">numThreads</span> = numThreads;
8261cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span> = [];
8271cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span> = [];
8281cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span> = [];
8291cb0ef41Sopenharmony_ci
8301cb0ef41Sopenharmony_ci    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numThreads; i++)
8311cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
8321cb0ef41Sopenharmony_ci
8331cb0ef41Sopenharmony_ci    <span class="hljs-comment">// Any time the kWorkerFreedEvent is emitted, dispatch</span>
8341cb0ef41Sopenharmony_ci    <span class="hljs-comment">// the next task pending in the queue, if any.</span>
8351cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">on</span>(kWorkerFreedEvent, <span class="hljs-function">() =></span> {
8361cb0ef41Sopenharmony_ci      <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-property">length</span> > <span class="hljs-number">0</span>) {
8371cb0ef41Sopenharmony_ci        <span class="hljs-keyword">const</span> { task, callback } = <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">shift</span>();
8381cb0ef41Sopenharmony_ci        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runTask</span>(task, callback);
8391cb0ef41Sopenharmony_ci      }
8401cb0ef41Sopenharmony_ci    });
8411cb0ef41Sopenharmony_ci  }
8421cb0ef41Sopenharmony_ci
8431cb0ef41Sopenharmony_ci  <span class="hljs-title function_">addNewWorker</span>(<span class="hljs-params"></span>) {
8441cb0ef41Sopenharmony_ci    <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'task_processor.js'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));
8451cb0ef41Sopenharmony_ci    worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
8461cb0ef41Sopenharmony_ci      <span class="hljs-comment">// In case of success: Call the callback that was passed to `runTask`,</span>
8471cb0ef41Sopenharmony_ci      <span class="hljs-comment">// remove the `TaskInfo` associated with the Worker, and mark it as free</span>
8481cb0ef41Sopenharmony_ci      <span class="hljs-comment">// again.</span>
8491cb0ef41Sopenharmony_ci      worker[kTaskInfo].<span class="hljs-title function_">done</span>(<span class="hljs-literal">null</span>, result);
8501cb0ef41Sopenharmony_ci      worker[kTaskInfo] = <span class="hljs-literal">null</span>;
8511cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
8521cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
8531cb0ef41Sopenharmony_ci    });
8541cb0ef41Sopenharmony_ci    worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
8551cb0ef41Sopenharmony_ci      <span class="hljs-comment">// In case of an uncaught exception: Call the callback that was passed to</span>
8561cb0ef41Sopenharmony_ci      <span class="hljs-comment">// `runTask` with the error.</span>
8571cb0ef41Sopenharmony_ci      <span class="hljs-keyword">if</span> (worker[kTaskInfo])
8581cb0ef41Sopenharmony_ci        worker[kTaskInfo].<span class="hljs-title function_">done</span>(err, <span class="hljs-literal">null</span>);
8591cb0ef41Sopenharmony_ci      <span class="hljs-keyword">else</span>
8601cb0ef41Sopenharmony_ci        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
8611cb0ef41Sopenharmony_ci      <span class="hljs-comment">// Remove the worker from the list and start a new Worker to replace the</span>
8621cb0ef41Sopenharmony_ci      <span class="hljs-comment">// current one.</span>
8631cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">splice</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">indexOf</span>(worker), <span class="hljs-number">1</span>);
8641cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
8651cb0ef41Sopenharmony_ci    });
8661cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">push</span>(worker);
8671cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
8681cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
8691cb0ef41Sopenharmony_ci  }
8701cb0ef41Sopenharmony_ci
8711cb0ef41Sopenharmony_ci  <span class="hljs-title function_">runTask</span>(<span class="hljs-params">task, callback</span>) {
8721cb0ef41Sopenharmony_ci    <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-property">length</span> === <span class="hljs-number">0</span>) {
8731cb0ef41Sopenharmony_ci      <span class="hljs-comment">// No free threads, wait until a worker thread becomes free.</span>
8741cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">push</span>({ task, callback });
8751cb0ef41Sopenharmony_ci      <span class="hljs-keyword">return</span>;
8761cb0ef41Sopenharmony_ci    }
8771cb0ef41Sopenharmony_ci
8781cb0ef41Sopenharmony_ci    <span class="hljs-keyword">const</span> worker = <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">pop</span>();
8791cb0ef41Sopenharmony_ci    worker[kTaskInfo] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span>(callback);
8801cb0ef41Sopenharmony_ci    worker.<span class="hljs-title function_">postMessage</span>(task);
8811cb0ef41Sopenharmony_ci  }
8821cb0ef41Sopenharmony_ci
8831cb0ef41Sopenharmony_ci  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
8841cb0ef41Sopenharmony_ci    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>) worker.<span class="hljs-title function_">terminate</span>();
8851cb0ef41Sopenharmony_ci  }
8861cb0ef41Sopenharmony_ci}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
8871cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
8881cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
8891cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
8901cb0ef41Sopenharmony_ci
8911cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> kTaskInfo = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kTaskInfo'</span>);
8921cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> kWorkerFreedEvent = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kWorkerFreedEvent'</span>);
8931cb0ef41Sopenharmony_ci
8941cb0ef41Sopenharmony_ci<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
8951cb0ef41Sopenharmony_ci  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">callback</span>) {
8961cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'WorkerPoolTaskInfo'</span>);
8971cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span> = callback;
8981cb0ef41Sopenharmony_ci  }
8991cb0ef41Sopenharmony_ci
9001cb0ef41Sopenharmony_ci  <span class="hljs-title function_">done</span>(<span class="hljs-params">err, result</span>) {
9011cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span>, <span class="hljs-literal">null</span>, err, result);
9021cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>();  <span class="hljs-comment">// `TaskInfo`s are used only once.</span>
9031cb0ef41Sopenharmony_ci  }
9041cb0ef41Sopenharmony_ci}
9051cb0ef41Sopenharmony_ci
9061cb0ef41Sopenharmony_ci<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPool</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
9071cb0ef41Sopenharmony_ci  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">numThreads</span>) {
9081cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">super</span>();
9091cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">numThreads</span> = numThreads;
9101cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span> = [];
9111cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span> = [];
9121cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span> = [];
9131cb0ef41Sopenharmony_ci
9141cb0ef41Sopenharmony_ci    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numThreads; i++)
9151cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
9161cb0ef41Sopenharmony_ci
9171cb0ef41Sopenharmony_ci    <span class="hljs-comment">// Any time the kWorkerFreedEvent is emitted, dispatch</span>
9181cb0ef41Sopenharmony_ci    <span class="hljs-comment">// the next task pending in the queue, if any.</span>
9191cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">on</span>(kWorkerFreedEvent, <span class="hljs-function">() =></span> {
9201cb0ef41Sopenharmony_ci      <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-property">length</span> > <span class="hljs-number">0</span>) {
9211cb0ef41Sopenharmony_ci        <span class="hljs-keyword">const</span> { task, callback } = <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">shift</span>();
9221cb0ef41Sopenharmony_ci        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runTask</span>(task, callback);
9231cb0ef41Sopenharmony_ci      }
9241cb0ef41Sopenharmony_ci    });
9251cb0ef41Sopenharmony_ci  }
9261cb0ef41Sopenharmony_ci
9271cb0ef41Sopenharmony_ci  <span class="hljs-title function_">addNewWorker</span>(<span class="hljs-params"></span>) {
9281cb0ef41Sopenharmony_ci    <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(path.<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'task_processor.js'</span>));
9291cb0ef41Sopenharmony_ci    worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
9301cb0ef41Sopenharmony_ci      <span class="hljs-comment">// In case of success: Call the callback that was passed to `runTask`,</span>
9311cb0ef41Sopenharmony_ci      <span class="hljs-comment">// remove the `TaskInfo` associated with the Worker, and mark it as free</span>
9321cb0ef41Sopenharmony_ci      <span class="hljs-comment">// again.</span>
9331cb0ef41Sopenharmony_ci      worker[kTaskInfo].<span class="hljs-title function_">done</span>(<span class="hljs-literal">null</span>, result);
9341cb0ef41Sopenharmony_ci      worker[kTaskInfo] = <span class="hljs-literal">null</span>;
9351cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
9361cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
9371cb0ef41Sopenharmony_ci    });
9381cb0ef41Sopenharmony_ci    worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
9391cb0ef41Sopenharmony_ci      <span class="hljs-comment">// In case of an uncaught exception: Call the callback that was passed to</span>
9401cb0ef41Sopenharmony_ci      <span class="hljs-comment">// `runTask` with the error.</span>
9411cb0ef41Sopenharmony_ci      <span class="hljs-keyword">if</span> (worker[kTaskInfo])
9421cb0ef41Sopenharmony_ci        worker[kTaskInfo].<span class="hljs-title function_">done</span>(err, <span class="hljs-literal">null</span>);
9431cb0ef41Sopenharmony_ci      <span class="hljs-keyword">else</span>
9441cb0ef41Sopenharmony_ci        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
9451cb0ef41Sopenharmony_ci      <span class="hljs-comment">// Remove the worker from the list and start a new Worker to replace the</span>
9461cb0ef41Sopenharmony_ci      <span class="hljs-comment">// current one.</span>
9471cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">splice</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">indexOf</span>(worker), <span class="hljs-number">1</span>);
9481cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
9491cb0ef41Sopenharmony_ci    });
9501cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">push</span>(worker);
9511cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
9521cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
9531cb0ef41Sopenharmony_ci  }
9541cb0ef41Sopenharmony_ci
9551cb0ef41Sopenharmony_ci  <span class="hljs-title function_">runTask</span>(<span class="hljs-params">task, callback</span>) {
9561cb0ef41Sopenharmony_ci    <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-property">length</span> === <span class="hljs-number">0</span>) {
9571cb0ef41Sopenharmony_ci      <span class="hljs-comment">// No free threads, wait until a worker thread becomes free.</span>
9581cb0ef41Sopenharmony_ci      <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">push</span>({ task, callback });
9591cb0ef41Sopenharmony_ci      <span class="hljs-keyword">return</span>;
9601cb0ef41Sopenharmony_ci    }
9611cb0ef41Sopenharmony_ci
9621cb0ef41Sopenharmony_ci    <span class="hljs-keyword">const</span> worker = <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">pop</span>();
9631cb0ef41Sopenharmony_ci    worker[kTaskInfo] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span>(callback);
9641cb0ef41Sopenharmony_ci    worker.<span class="hljs-title function_">postMessage</span>(task);
9651cb0ef41Sopenharmony_ci  }
9661cb0ef41Sopenharmony_ci
9671cb0ef41Sopenharmony_ci  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
9681cb0ef41Sopenharmony_ci    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>) worker.<span class="hljs-title function_">terminate</span>();
9691cb0ef41Sopenharmony_ci  }
9701cb0ef41Sopenharmony_ci}
9711cb0ef41Sopenharmony_ci
9721cb0ef41Sopenharmony_ci<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-title class_">WorkerPool</span>;</code><button class="copy-button">copy</button></pre>
9731cb0ef41Sopenharmony_ci<p>Without the explicit tracking added by the <code>WorkerPoolTaskInfo</code> objects,
9741cb0ef41Sopenharmony_ciit would appear that the callbacks are associated with the individual <code>Worker</code>
9751cb0ef41Sopenharmony_ciobjects. However, the creation of the <code>Worker</code>s is not associated with the
9761cb0ef41Sopenharmony_cicreation of the tasks and does not provide information about when tasks
9771cb0ef41Sopenharmony_ciwere scheduled.</p>
9781cb0ef41Sopenharmony_ci<p>This pool could be used as follows:</p>
9791cb0ef41Sopenharmony_ci
9801cb0ef41Sopenharmony_ci<pre class="with-47-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> <span class="hljs-title class_">WorkerPool</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'./worker_pool.js'</span>;
9811cb0ef41Sopenharmony_ci<span class="hljs-keyword">import</span> os <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
9821cb0ef41Sopenharmony_ci
9831cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> pool = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPool</span>(os.<span class="hljs-title function_">availableParallelism</span>());
9841cb0ef41Sopenharmony_ci
9851cb0ef41Sopenharmony_ci<span class="hljs-keyword">let</span> finished = <span class="hljs-number">0</span>;
9861cb0ef41Sopenharmony_ci<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; i++) {
9871cb0ef41Sopenharmony_ci  pool.<span class="hljs-title function_">runTask</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">42</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">100</span> }, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =></span> {
9881cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i, err, result);
9891cb0ef41Sopenharmony_ci    <span class="hljs-keyword">if</span> (++finished === <span class="hljs-number">10</span>)
9901cb0ef41Sopenharmony_ci      pool.<span class="hljs-title function_">close</span>();
9911cb0ef41Sopenharmony_ci  });
9921cb0ef41Sopenharmony_ci}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">WorkerPool</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./worker_pool.js'</span>);
9931cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> os = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>);
9941cb0ef41Sopenharmony_ci
9951cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> pool = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPool</span>(os.<span class="hljs-title function_">availableParallelism</span>());
9961cb0ef41Sopenharmony_ci
9971cb0ef41Sopenharmony_ci<span class="hljs-keyword">let</span> finished = <span class="hljs-number">0</span>;
9981cb0ef41Sopenharmony_ci<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; i++) {
9991cb0ef41Sopenharmony_ci  pool.<span class="hljs-title function_">runTask</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">42</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">100</span> }, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =></span> {
10001cb0ef41Sopenharmony_ci    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i, err, result);
10011cb0ef41Sopenharmony_ci    <span class="hljs-keyword">if</span> (++finished === <span class="hljs-number">10</span>)
10021cb0ef41Sopenharmony_ci      pool.<span class="hljs-title function_">close</span>();
10031cb0ef41Sopenharmony_ci  });
10041cb0ef41Sopenharmony_ci}</code><button class="copy-button">copy</button></pre>
10051cb0ef41Sopenharmony_ci<h4>Integrating <code>AsyncResource</code> with <code>EventEmitter</code><span><a class="mark" href="#integrating-asyncresource-with-eventemitter" id="integrating-asyncresource-with-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="async_context_integrating_asyncresource_with_eventemitter"></a></h4>
10061cb0ef41Sopenharmony_ci<p>Event listeners triggered by an <a href="events.html#class-eventemitter"><code>EventEmitter</code></a> may be run in a different
10071cb0ef41Sopenharmony_ciexecution context than the one that was active when <code>eventEmitter.on()</code> was
10081cb0ef41Sopenharmony_cicalled.</p>
10091cb0ef41Sopenharmony_ci<p>The following example shows how to use the <code>AsyncResource</code> class to properly
10101cb0ef41Sopenharmony_ciassociate an event listener with the correct execution context. The same
10111cb0ef41Sopenharmony_ciapproach can be applied to a <a href="stream.html#stream"><code>Stream</code></a> or a similar event-driven class.</p>
10121cb0ef41Sopenharmony_ci
10131cb0ef41Sopenharmony_ci<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:http'</span>;
10141cb0ef41Sopenharmony_ci<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
10151cb0ef41Sopenharmony_ci
10161cb0ef41Sopenharmony_ci<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> {
10171cb0ef41Sopenharmony_ci  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-title class_">AsyncResource</span>.<span class="hljs-title function_">bind</span>(<span class="hljs-function">() =></span> {
10181cb0ef41Sopenharmony_ci    <span class="hljs-comment">// Execution context is bound to the current outer scope.</span>
10191cb0ef41Sopenharmony_ci  }));
10201cb0ef41Sopenharmony_ci  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
10211cb0ef41Sopenharmony_ci    <span class="hljs-comment">// Execution context is bound to the scope that caused 'close' to emit.</span>
10221cb0ef41Sopenharmony_ci  });
10231cb0ef41Sopenharmony_ci  res.<span class="hljs-title function_">end</span>();
10241cb0ef41Sopenharmony_ci}).<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>);
10251cb0ef41Sopenharmony_ci<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
10261cb0ef41Sopenharmony_ci
10271cb0ef41Sopenharmony_ci<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> {
10281cb0ef41Sopenharmony_ci  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-title class_">AsyncResource</span>.<span class="hljs-title function_">bind</span>(<span class="hljs-function">() =></span> {
10291cb0ef41Sopenharmony_ci    <span class="hljs-comment">// Execution context is bound to the current outer scope.</span>
10301cb0ef41Sopenharmony_ci  }));
10311cb0ef41Sopenharmony_ci  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
10321cb0ef41Sopenharmony_ci    <span class="hljs-comment">// Execution context is bound to the scope that caused 'close' to emit.</span>
10331cb0ef41Sopenharmony_ci  });
10341cb0ef41Sopenharmony_ci  res.<span class="hljs-title function_">end</span>();
10351cb0ef41Sopenharmony_ci}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre></section>
10361cb0ef41Sopenharmony_ci        <!-- API END -->
10371cb0ef41Sopenharmony_ci      </div>
10381cb0ef41Sopenharmony_ci    </div>
10391cb0ef41Sopenharmony_ci  </div>
10401cb0ef41Sopenharmony_ci</body>
10411cb0ef41Sopenharmony_ci</html>
1042