File: async_context.html

package info (click to toggle)
nodejs 22.14.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 246,928 kB
  • sloc: cpp: 1,582,349; javascript: 582,017; ansic: 82,400; python: 60,561; sh: 4,009; makefile: 2,263; asm: 1,732; pascal: 1,565; perl: 248; lisp: 222; xml: 42
file content (1060 lines) | stat: -rw-r--r-- 87,179 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <meta name="nodejs.org:node-version" content="v22.14.0">
  <title>Asynchronous context tracking | Node.js v22.14.0 Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/hljs.css">
  <link rel="canonical" href="https://nodejs.org/api/async_context.html">
  <script async defer src="assets/api.js" type="text/javascript"></script>
  <script>
      const storedTheme = localStorage.getItem('theme');

      // Follow operating system theme preference
      if (storedTheme === null && window.matchMedia) {
        const mq = window.matchMedia('(prefers-color-scheme: dark)');
        if (mq.matches) {
          document.documentElement.classList.add('dark-mode');
        }
      } else if (storedTheme === 'dark') {
        document.documentElement.classList.add('dark-mode');
      }
  </script>
  <style>@media(max-width:1080px){.with-73-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:686px){.with-58-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1072px){.with-72-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:654px){.with-54-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:598px){.with-47-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}</style>
</head>
<body class="alt apidoc" id="api-section-async_context">
  <a href="#apicontent" class="skip-to-content">Skip to content</a>
  <div id="content" class="clearfix">
    <div role="navigation" id="column2" class="interior">
      <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
          Node.js
        </a>
      </div>
      <ul>
<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_context.html" class="nav-async_context active">Asynchronous context tracking</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
<li><a href="typescript.html" class="nav-typescript">Modules: TypeScript</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="report.html" class="nav-report">Report</a></li>
<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
<li><a href="sqlite.html" class="nav-sqlite">SQLite</a></li>
<li><a href="stream.html" class="nav-stream">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
<li><a href="test.html" class="nav-test">Test runner</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
</ul>
    </div>

    <div id="column1" data-id="async_context" class="interior">
      <header class="header">
        <div class="header-container">
          <h1>Node.js v22.14.0 documentation</h1>
          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
              <path fill="none" d="M0 0h24v24H0z" />
              <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"/>
              <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"/>
            </svg>
            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
              <path d="M0 0h24v24H0z" fill="none" />
              <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"/>
            </svg>
          </button>
        </div>
        <div id="gtoc">
          <ul>
            <li class="pinned-header">Node.js v22.14.0</li>
            
    <li class="picker-header">
      <a href="#toc-picker" aria-controls="toc-picker">
        <span class="picker-arrow"></span>
        Table of contents
      </a>

      <div class="picker" tabindex="-1"><div class="toc"><ul id="toc-picker">
<li><span class="stability_2"><a href="#asynchronous-context-tracking">Asynchronous context tracking</a></span>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#class-asynclocalstorage">Class: <code>AsyncLocalStorage</code></a>
<ul>
<li><a href="#new-asynclocalstorage"><code>new AsyncLocalStorage()</code></a></li>
<li><span class="stability_1"><a href="#static-method-asynclocalstoragebindfn">Static method: <code>AsyncLocalStorage.bind(fn)</code></a></span></li>
<li><span class="stability_1"><a href="#static-method-asynclocalstoragesnapshot">Static method: <code>AsyncLocalStorage.snapshot()</code></a></span></li>
<li><span class="stability_1"><a href="#asynclocalstoragedisable"><code>asyncLocalStorage.disable()</code></a></span></li>
<li><a href="#asynclocalstoragegetstore"><code>asyncLocalStorage.getStore()</code></a></li>
<li><span class="stability_1"><a href="#asynclocalstorageenterwithstore"><code>asyncLocalStorage.enterWith(store)</code></a></span></li>
<li><a href="#asynclocalstoragerunstore-callback-args"><code>asyncLocalStorage.run(store, callback[, ...args])</code></a></li>
<li><span class="stability_1"><a href="#asynclocalstorageexitcallback-args"><code>asyncLocalStorage.exit(callback[, ...args])</code></a></span></li>
<li><a href="#usage-with-asyncawait">Usage with <code>async/await</code></a></li>
<li><a href="#troubleshooting-context-loss">Troubleshooting: Context loss</a></li>
</ul>
</li>
<li><a href="#class-asyncresource">Class: <code>AsyncResource</code></a>
<ul>
<li><a href="#new-asyncresourcetype-options"><code>new AsyncResource(type[, options])</code></a></li>
<li><a href="#static-method-asyncresourcebindfn-type-thisarg">Static method: <code>AsyncResource.bind(fn[, type[, thisArg]])</code></a></li>
<li><a href="#asyncresourcebindfn-thisarg"><code>asyncResource.bind(fn[, thisArg])</code></a></li>
<li><a href="#asyncresourceruninasyncscopefn-thisarg-args"><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code></a></li>
<li><a href="#asyncresourceemitdestroy"><code>asyncResource.emitDestroy()</code></a></li>
<li><a href="#asyncresourceasyncid"><code>asyncResource.asyncId()</code></a></li>
<li><a href="#asyncresourcetriggerasyncid"><code>asyncResource.triggerAsyncId()</code></a></li>
<li><a href="#using-asyncresource-for-a-worker-thread-pool">Using <code>AsyncResource</code> for a <code>Worker</code> thread pool</a></li>
<li><a href="#integrating-asyncresource-with-eventemitter">Integrating <code>AsyncResource</code> with <code>EventEmitter</code></a></li>
</ul>
</li>
</ul>
</li>
</ul></div></div>
    </li>
  
            
    <li class="picker-header">
      <a href="#gtoc-picker" aria-controls="gtoc-picker">
        <span class="picker-arrow"></span>
        Index
      </a>

      <div class="picker" tabindex="-1" id="gtoc-picker"><ul>
<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>

      <li>
        <a href="index.html">Index</a>
      </li>
    </ul>
  
<hr class="line">
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_context.html" class="nav-async_context active">Asynchronous context tracking</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
<li><a href="typescript.html" class="nav-typescript">Modules: TypeScript</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="report.html" class="nav-report">Report</a></li>
<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
<li><a href="sqlite.html" class="nav-sqlite">SQLite</a></li>
<li><a href="stream.html" class="nav-stream">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
<li><a href="test.html" class="nav-test">Test runner</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
</ul></div>
    </li>
  
            
    <li class="picker-header">
      <a href="#alt-docs" aria-controls="alt-docs">
        <span class="picker-arrow"></span>
        Other versions
      </a>
      <div class="picker" tabindex="-1"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v23.x/api/async_context.html">23.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v22.x/api/async_context.html">22.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v21.x/api/async_context.html">21.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v20.x/api/async_context.html">20.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v19.x/api/async_context.html">19.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v18.x/api/async_context.html">18.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v17.x/api/async_context.html">17.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v16.x/api/async_context.html">16.x</a></li></ol></div>
    </li>
  
            <li class="picker-header">
              <a href="#options-picker" aria-controls="options-picker">
                <span class="picker-arrow"></span>
                Options
              </a>
        
              <div class="picker" tabindex="-1">
                <ul id="options-picker">
                  <li>
                    <a href="all.html">View on single page</a>
                  </li>
                  <li>
                    <a href="async_context.json">View as JSON</a>
                  </li>
                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/async_context.md">Edit on GitHub</a></li>    
                </ul>
              </div>
            </li>
          </ul>
        </div>
        <hr>
      </header>

      <details role="navigation" id="toc" open><summary>Table of contents</summary><ul>
<li><span class="stability_2"><a href="#asynchronous-context-tracking">Asynchronous context tracking</a></span>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#class-asynclocalstorage">Class: <code>AsyncLocalStorage</code></a>
<ul>
<li><a href="#new-asynclocalstorage"><code>new AsyncLocalStorage()</code></a></li>
<li><span class="stability_1"><a href="#static-method-asynclocalstoragebindfn">Static method: <code>AsyncLocalStorage.bind(fn)</code></a></span></li>
<li><span class="stability_1"><a href="#static-method-asynclocalstoragesnapshot">Static method: <code>AsyncLocalStorage.snapshot()</code></a></span></li>
<li><span class="stability_1"><a href="#asynclocalstoragedisable"><code>asyncLocalStorage.disable()</code></a></span></li>
<li><a href="#asynclocalstoragegetstore"><code>asyncLocalStorage.getStore()</code></a></li>
<li><span class="stability_1"><a href="#asynclocalstorageenterwithstore"><code>asyncLocalStorage.enterWith(store)</code></a></span></li>
<li><a href="#asynclocalstoragerunstore-callback-args"><code>asyncLocalStorage.run(store, callback[, ...args])</code></a></li>
<li><span class="stability_1"><a href="#asynclocalstorageexitcallback-args"><code>asyncLocalStorage.exit(callback[, ...args])</code></a></span></li>
<li><a href="#usage-with-asyncawait">Usage with <code>async/await</code></a></li>
<li><a href="#troubleshooting-context-loss">Troubleshooting: Context loss</a></li>
</ul>
</li>
<li><a href="#class-asyncresource">Class: <code>AsyncResource</code></a>
<ul>
<li><a href="#new-asyncresourcetype-options"><code>new AsyncResource(type[, options])</code></a></li>
<li><a href="#static-method-asyncresourcebindfn-type-thisarg">Static method: <code>AsyncResource.bind(fn[, type[, thisArg]])</code></a></li>
<li><a href="#asyncresourcebindfn-thisarg"><code>asyncResource.bind(fn[, thisArg])</code></a></li>
<li><a href="#asyncresourceruninasyncscopefn-thisarg-args"><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code></a></li>
<li><a href="#asyncresourceemitdestroy"><code>asyncResource.emitDestroy()</code></a></li>
<li><a href="#asyncresourceasyncid"><code>asyncResource.asyncId()</code></a></li>
<li><a href="#asyncresourcetriggerasyncid"><code>asyncResource.triggerAsyncId()</code></a></li>
<li><a href="#using-asyncresource-for-a-worker-thread-pool">Using <code>AsyncResource</code> for a <code>Worker</code> thread pool</a></li>
<li><a href="#integrating-asyncresource-with-eventemitter">Integrating <code>AsyncResource</code> with <code>EventEmitter</code></a></li>
</ul>
</li>
</ul>
</li>
</ul></details>

      <div role="main" id="apicontent">
        <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>

<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v22.14.0/lib/async_hooks.js">lib/async_hooks.js</a></p>
<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>
<p>These classes are used to associate state and propagate it throughout
callbacks and promise chains.
They allow storing data throughout the lifetime of a web request
or any other asynchronous duration. It is similar to thread-local storage
in other languages.</p>
<p>The <code>AsyncLocalStorage</code> and <code>AsyncResource</code> classes are part of the
<code>node:async_hooks</code> module:</p>

<pre class="with-73-chars"><input class="js-flavor-toggle" 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>
</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>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0</td>
<td><p>AsyncLocalStorage is now Stable. Previously, it had been Experimental.</p></td></tr>
<tr><td>v13.10.0, v12.17.0</td>
<td><p><span>Added in: v13.10.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>This class creates stores that stay coherent through asynchronous operations.</p>
<p>While you can create your own implementation on top of the <code>node:async_hooks</code>
module, <code>AsyncLocalStorage</code> should be preferred as it is a performant and memory
safe implementation that involves significant optimizations that are non-obvious
to implement.</p>
<p>The following example uses <code>AsyncLocalStorage</code> to build a simple logger
that assigns IDs to incoming HTTP requests and includes them in messages
logged within each request.</p>

<pre class="with-58-chars"><input class="js-flavor-toggle" 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>;
<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>;

<span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">logWithId</span>(<span class="hljs-params">msg</span>) {
  <span class="hljs-keyword">const</span> id = asyncLocalStorage.<span class="hljs-title function_">getStore</span>();
  <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);
}

<span class="hljs-keyword">let</span> idSeq = <span class="hljs-number">0</span>;
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  asyncLocalStorage.<span class="hljs-title function_">run</span>(idSeq++, <span class="hljs-function">() =></span> {
    <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'start'</span>);
    <span class="hljs-comment">// Imagine any chain of async operations here</span>
    <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
      <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'finish'</span>);
      res.<span class="hljs-title function_">end</span>();
    });
  });
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);

http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   0: start</span>
<span class="hljs-comment">//   1: start</span>
<span class="hljs-comment">//   0: finish</span>
<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>);
<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>);

<span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">logWithId</span>(<span class="hljs-params">msg</span>) {
  <span class="hljs-keyword">const</span> id = asyncLocalStorage.<span class="hljs-title function_">getStore</span>();
  <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);
}

<span class="hljs-keyword">let</span> idSeq = <span class="hljs-number">0</span>;
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  asyncLocalStorage.<span class="hljs-title function_">run</span>(idSeq++, <span class="hljs-function">() =></span> {
    <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'start'</span>);
    <span class="hljs-comment">// Imagine any chain of async operations here</span>
    <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
      <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'finish'</span>);
      res.<span class="hljs-title function_">end</span>();
    });
  });
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);

http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   0: start</span>
<span class="hljs-comment">//   1: start</span>
<span class="hljs-comment">//   0: finish</span>
<span class="hljs-comment">//   1: finish</span></code><button class="copy-button">copy</button></pre>
<p>Each instance of <code>AsyncLocalStorage</code> maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.</p>
<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>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.7.0, v18.16.0</td>
<td><p>Removed experimental onPropagate option.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>Add option onPropagate.</p></td></tr>
<tr><td>v13.10.0, v12.17.0</td>
<td><p><span>Added in: v13.10.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Creates a new instance of <code>AsyncLocalStorage</code>. Store is only provided within a
<code>run()</code> call or after an <code>enterWith()</code> call.</p>
<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>
<div class="api_metadata">
<span>Added in: v19.8.0, v18.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<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>
<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
execution context.</li>
</ul>
<p>Binds the given function to the current execution context.</p>
<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>
<div class="api_metadata">
<span>Added in: v19.8.0, v18.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<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
<code>(fn: (...args) : R, ...args) : R</code>.</li>
</ul>
<p>Captures the current execution context and returns a function that accepts a
function as an argument. Whenever the returned function is called, it
calls the function passed to it within the captured context.</p>
<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>();
<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>());
<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>()));
<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>
<p>AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
async context tracking purposes, for example:</p>
<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
  #runInAsyncScope = <span class="hljs-title class_">AsyncLocalStorage</span>.<span class="hljs-title function_">snapshot</span>();

  <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>()); }
}

<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>());
<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>
<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>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Disables the instance of <code>AsyncLocalStorage</code>. All subsequent calls
to <code>asyncLocalStorage.getStore()</code> will return <code>undefined</code> until
<code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code> is called again.</p>
<p>When calling <code>asyncLocalStorage.disable()</code>, all current contexts linked to the
instance will be exited.</p>
<p>Calling <code>asyncLocalStorage.disable()</code> is required before the
<code>asyncLocalStorage</code> can be garbage collected. This does not apply to stores
provided by the <code>asyncLocalStorage</code>, as those objects are garbage collected
along with the corresponding async resources.</p>
<p>Use this method when the <code>asyncLocalStorage</code> is not in use anymore
in the current process.</p>
<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>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Returns the current store.
If called outside of an asynchronous context initialized by
calling <code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code>, it
returns <code>undefined</code>.</p>
<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>
<div class="api_metadata">
<span>Added in: v13.11.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<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>
</ul>
<p>Transitions into the context for the remainder of the current
synchronous execution and then persists the store through any following
asynchronous calls.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
<span class="hljs-comment">// Replaces previous store with the given store object</span>
asyncLocalStorage.<span class="hljs-title function_">enterWith</span>(store);
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
<span class="hljs-title function_">someAsyncOperation</span>(<span class="hljs-function">() =></span> {
  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span>
});</code> <button class="copy-button">copy</button></pre>
<p>This transition will continue for the <em>entire</em> synchronous execution.
This means that if, for example, the context is entered within an event
handler subsequent event handlers will also run within that context unless
specifically bound to another context with an <code>AsyncResource</code>. That is why
<code>run()</code> should be preferred over <code>enterWith()</code> unless there are strong reasons
to use the latter method.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };

emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'my-event'</span>, <span class="hljs-function">() =></span> {
  asyncLocalStorage.<span class="hljs-title function_">enterWith</span>(store);
});
emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'my-event'</span>, <span class="hljs-function">() =></span> {
  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span>
});

asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
emitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'my-event'</span>);
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span></code> <button class="copy-button">copy</button></pre>
<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>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<ul>
<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>
<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>
<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>
</ul>
<p>Runs a function synchronously within a context and returns its
return value. The store is not accessible outside of the callback function.
The store is accessible to any asynchronous operations created within the
callback.</p>
<p>The optional <code>args</code> are passed to the callback function.</p>
<p>If the callback function throws an error, the error is thrown by <code>run()</code> too.
The stacktrace is not impacted by this call and the context is exited.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">try</span> {
  asyncLocalStorage.<span class="hljs-title function_">run</span>(store, <span class="hljs-function">() =></span> {
    asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
      asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
    }, <span class="hljs-number">200</span>);
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
  });
} <span class="hljs-keyword">catch</span> (e) {
  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
  <span class="hljs-comment">// The error will be caught here</span>
}</code> <button class="copy-button">copy</button></pre>
<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>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<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>
<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>
</ul>
<p>Runs a function synchronously outside of a context and returns its
return value. The store is not accessible within the callback function or
the asynchronous operations created within the callback. Any <code>getStore()</code>
call done within the callback function will always return <code>undefined</code>.</p>
<p>The optional <code>args</code> are passed to the callback function.</p>
<p>If the callback function throws an error, the error is thrown by <code>exit()</code> too.
The stacktrace is not impacted by this call and the context is re-entered.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-comment">// Within a call to run</span>
<span class="hljs-keyword">try</span> {
  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object or value</span>
  asyncLocalStorage.<span class="hljs-title function_">exit</span>(<span class="hljs-function">() =></span> {
    asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
  });
} <span class="hljs-keyword">catch</span> (e) {
  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object or value</span>
  <span class="hljs-comment">// The error will be caught here</span>
}</code> <button class="copy-button">copy</button></pre>
<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>
<p>If, within an async function, only one <code>await</code> call is to run within a context,
the following pattern should be used:</p>
<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>) {
  <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> {
    asyncLocalStorage.<span class="hljs-title function_">getStore</span>().<span class="hljs-title function_">set</span>(<span class="hljs-string">'key'</span>, value);
    <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>
  });
}</code> <button class="copy-button">copy</button></pre>
<p>In this example, the store is only available in the callback function and the
functions called by <code>foo</code>. Outside of <code>run</code>, calling <code>getStore</code> will return
<code>undefined</code>.</p>
<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>
<p>In most cases, <code>AsyncLocalStorage</code> works without issues. In rare situations, the
current store is lost in one of the asynchronous operations.</p>
<p>If your code is callback-based, it is enough to promisify it with
<a href="util.html#utilpromisifyoriginal"><code>util.promisify()</code></a> so it starts working with native promises.</p>
<p>If you need to use a callback-based API or your code assumes
a custom thenable implementation, use the <a href="#class-asyncresource"><code>AsyncResource</code></a> class
to associate the asynchronous operation with the correct execution context.
Find the function call responsible for the context loss by logging the content
of <code>asyncLocalStorage.getStore()</code> after the calls you suspect are responsible
for the loss. When the code logs <code>undefined</code>, the last callback called is
probably responsible for the context loss.</p>
</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>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0</td>
<td><p>AsyncResource is now Stable. Previously, it had been Experimental.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The class <code>AsyncResource</code> is designed to be extended by the embedder's async
resources. Using this, users can easily trigger the lifetime events of their
own resources.</p>
<p>The <code>init</code> hook will trigger when an <code>AsyncResource</code> is instantiated.</p>
<p>The following is an overview of the <code>AsyncResource</code> API.</p>

<pre class="with-72-chars"><input class="js-flavor-toggle" 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>;

<span class="hljs-comment">// AsyncResource() is meant to be extended. Instantiating a</span>
<span class="hljs-comment">// new AsyncResource() also triggers init. If triggerAsyncId is omitted then</span>
<span class="hljs-comment">// async_hook.executionAsyncId() is used.</span>
<span class="hljs-keyword">const</span> asyncResource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncResource</span>(
  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> },
);

<span class="hljs-comment">// Run a function in the execution context of the resource. This will</span>
<span class="hljs-comment">// * establish the context of the resource</span>
<span class="hljs-comment">// * trigger the AsyncHooks before callbacks</span>
<span class="hljs-comment">// * call the provided function `fn` with the supplied arguments</span>
<span class="hljs-comment">// * trigger the AsyncHooks after callbacks</span>
<span class="hljs-comment">// * restore the original execution context</span>
asyncResource.<span class="hljs-title function_">runInAsyncScope</span>(fn, thisArg, ...args);

<span class="hljs-comment">// Call AsyncHooks destroy callbacks.</span>
asyncResource.<span class="hljs-title function_">emitDestroy</span>();

<span class="hljs-comment">// Return the unique ID assigned to the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">asyncId</span>();

<span class="hljs-comment">// Return the trigger ID for the AsyncResource instance.</span>
asyncResource.<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>);

<span class="hljs-comment">// AsyncResource() is meant to be extended. Instantiating a</span>
<span class="hljs-comment">// new AsyncResource() also triggers init. If triggerAsyncId is omitted then</span>
<span class="hljs-comment">// async_hook.executionAsyncId() is used.</span>
<span class="hljs-keyword">const</span> asyncResource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncResource</span>(
  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> },
);

<span class="hljs-comment">// Run a function in the execution context of the resource. This will</span>
<span class="hljs-comment">// * establish the context of the resource</span>
<span class="hljs-comment">// * trigger the AsyncHooks before callbacks</span>
<span class="hljs-comment">// * call the provided function `fn` with the supplied arguments</span>
<span class="hljs-comment">// * trigger the AsyncHooks after callbacks</span>
<span class="hljs-comment">// * restore the original execution context</span>
asyncResource.<span class="hljs-title function_">runInAsyncScope</span>(fn, thisArg, ...args);

<span class="hljs-comment">// Call AsyncHooks destroy callbacks.</span>
asyncResource.<span class="hljs-title function_">emitDestroy</span>();

<span class="hljs-comment">// Return the unique ID assigned to the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">asyncId</span>();

<span class="hljs-comment">// Return the trigger ID for the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">triggerAsyncId</span>();</code><button class="copy-button">copy</button></pre>
<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>
<ul>
<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>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<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
async event. <strong>Default:</strong> <code>executionAsyncId()</code>.</li>
<li><code>requireManualDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to <code>true</code>, disables <code>emitDestroy</code>
when the object is garbage collected. This usually does not need to be set
(even if <code>emitDestroy</code> is called manually), unless the resource's <code>asyncId</code>
is retrieved and the sensitive API's <code>emitDestroy</code> is called with it.
When set to <code>false</code>, the <code>emitDestroy</code> call on garbage collection
will only take place if there is at least one active <code>destroy</code> hook.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Example usage:</p>
<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> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">db</span>) {
    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'DBQuery'</span>);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span> = db;
  }

  <span class="hljs-title function_">getInfo</span>(<span class="hljs-params">query, callback</span>) {
    <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> {
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(callback, <span class="hljs-literal">null</span>, err, data);
    });
  }

  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span> = <span class="hljs-literal">null</span>;
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>();
  }
}</code> <button class="copy-button">copy</button></pre>
<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>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The <code>asyncResource</code> property added to the bound function has been deprecated and will be removed in a future version.</p></td></tr>
<tr><td>v17.8.0, v16.15.0</td>
<td><p>Changed the default when <code>thisArg</code> is undefined to use <code>this</code> from the caller.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Added optional thisArg.</p></td></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<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>
<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
<code>AsyncResource</code>.</li>
<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>
</ul>
<p>Binds the given function to the current execution context.</p>
<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>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The <code>asyncResource</code> property added to the bound function has been deprecated and will be removed in a future version.</p></td></tr>
<tr><td>v17.8.0, v16.15.0</td>
<td><p>Changed the default when <code>thisArg</code> is undefined to use <code>this</code> from the caller.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Added optional thisArg.</p></td></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<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>
<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>
</ul>
<p>Binds the given function to execute to this <code>AsyncResource</code>'s scope.</p>
<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>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to call in the execution context of this async
resource.</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The receiver to be used for the function call.</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Optional arguments to pass to the function.</li>
</ul>
<p>Call the provided function with the provided arguments in the execution context
of the async resource. This will establish the context, trigger the AsyncHooks
before callbacks, call the function, trigger the AsyncHooks after callbacks, and
then restore the original execution context.</p>
<h4><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>
<ul>
<li>Returns: <a href="async_hooks.html#class-asyncresource" class="type">&#x3C;AsyncResource></a> A reference to <code>asyncResource</code>.</li>
</ul>
<p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will
be thrown if it is called more than once. This <strong>must</strong> be manually called. If
the resource is left to be collected by the GC then the <code>destroy</code> hooks will
never be called.</p>
<h4><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>
<ul>
<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>
</ul>
<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>
<ul>
<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
<code>AsyncResource</code> constructor.</li>
</ul>
<p><a id="async-resource-worker-pool"></a></p>
<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>
<p>The following example shows how to use the <code>AsyncResource</code> class to properly
provide async tracking for a <a href="worker_threads.html#class-worker"><code>Worker</code></a> pool. Other resource pools, such as
database connection pools, can follow a similar model.</p>
<p>Assuming that the task is adding two numbers, using a file named
<code>task_processor.js</code> with the following content:</p>

<pre class="with-54-chars"><input class="js-flavor-toggle" 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>;
parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">task</span>) =></span> {
  parentPort.<span class="hljs-title function_">postMessage</span>(task.<span class="hljs-property">a</span> + task.<span class="hljs-property">b</span>);
});</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>);
parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">task</span>) =></span> {
  parentPort.<span class="hljs-title function_">postMessage</span>(task.<span class="hljs-property">a</span> + task.<span class="hljs-property">b</span>);
});</code><button class="copy-button">copy</button></pre>
<p>a Worker pool around it could use the following structure:</p>

<pre class="with-54-chars"><input class="js-flavor-toggle" 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>;
<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>;
<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>;

<span class="hljs-keyword">const</span> kTaskInfo = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kTaskInfo'</span>);
<span class="hljs-keyword">const</span> kWorkerFreedEvent = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kWorkerFreedEvent'</span>);

<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> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">callback</span>) {
    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'WorkerPoolTaskInfo'</span>);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span> = callback;
  }

  <span class="hljs-title function_">done</span>(<span class="hljs-params">err, result</span>) {
    <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);
    <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>
  }
}

<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> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">numThreads</span>) {
    <span class="hljs-variable language_">super</span>();
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">numThreads</span> = numThreads;
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span> = [];
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span> = [];
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span> = [];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numThreads; i++)
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();

    <span class="hljs-comment">// Any time the kWorkerFreedEvent is emitted, dispatch</span>
    <span class="hljs-comment">// the next task pending in the queue, if any.</span>
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">on</span>(kWorkerFreedEvent, <span class="hljs-function">() =></span> {
      <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>) {
        <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>();
        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runTask</span>(task, callback);
      }
    });
  }

  <span class="hljs-title function_">addNewWorker</span>(<span class="hljs-params"></span>) {
    <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>));
    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> {
      <span class="hljs-comment">// In case of success: Call the callback that was passed to `runTask`,</span>
      <span class="hljs-comment">// remove the `TaskInfo` associated with the Worker, and mark it as free</span>
      <span class="hljs-comment">// again.</span>
      worker[kTaskInfo].<span class="hljs-title function_">done</span>(<span class="hljs-literal">null</span>, result);
      worker[kTaskInfo] = <span class="hljs-literal">null</span>;
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
    });
    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> {
      <span class="hljs-comment">// In case of an uncaught exception: Call the callback that was passed to</span>
      <span class="hljs-comment">// `runTask` with the error.</span>
      <span class="hljs-keyword">if</span> (worker[kTaskInfo])
        worker[kTaskInfo].<span class="hljs-title function_">done</span>(err, <span class="hljs-literal">null</span>);
      <span class="hljs-keyword">else</span>
        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
      <span class="hljs-comment">// Remove the worker from the list and start a new Worker to replace the</span>
      <span class="hljs-comment">// current one.</span>
      <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>);
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
    });
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">push</span>(worker);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
  }

  <span class="hljs-title function_">runTask</span>(<span class="hljs-params">task, callback</span>) {
    <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>) {
      <span class="hljs-comment">// No free threads, wait until a worker thread becomes free.</span>
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">push</span>({ task, callback });
      <span class="hljs-keyword">return</span>;
    }

    <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>();
    worker[kTaskInfo] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span>(callback);
    worker.<span class="hljs-title function_">postMessage</span>(task);
  }

  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
    <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>();
  }
}</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>);
<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>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<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>);

<span class="hljs-keyword">const</span> kTaskInfo = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kTaskInfo'</span>);
<span class="hljs-keyword">const</span> kWorkerFreedEvent = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kWorkerFreedEvent'</span>);

<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> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">callback</span>) {
    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'WorkerPoolTaskInfo'</span>);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span> = callback;
  }

  <span class="hljs-title function_">done</span>(<span class="hljs-params">err, result</span>) {
    <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);
    <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>
  }
}

<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> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">numThreads</span>) {
    <span class="hljs-variable language_">super</span>();
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">numThreads</span> = numThreads;
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span> = [];
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span> = [];
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span> = [];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numThreads; i++)
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();

    <span class="hljs-comment">// Any time the kWorkerFreedEvent is emitted, dispatch</span>
    <span class="hljs-comment">// the next task pending in the queue, if any.</span>
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">on</span>(kWorkerFreedEvent, <span class="hljs-function">() =></span> {
      <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>) {
        <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>();
        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runTask</span>(task, callback);
      }
    });
  }

  <span class="hljs-title function_">addNewWorker</span>(<span class="hljs-params"></span>) {
    <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>));
    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> {
      <span class="hljs-comment">// In case of success: Call the callback that was passed to `runTask`,</span>
      <span class="hljs-comment">// remove the `TaskInfo` associated with the Worker, and mark it as free</span>
      <span class="hljs-comment">// again.</span>
      worker[kTaskInfo].<span class="hljs-title function_">done</span>(<span class="hljs-literal">null</span>, result);
      worker[kTaskInfo] = <span class="hljs-literal">null</span>;
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
    });
    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> {
      <span class="hljs-comment">// In case of an uncaught exception: Call the callback that was passed to</span>
      <span class="hljs-comment">// `runTask` with the error.</span>
      <span class="hljs-keyword">if</span> (worker[kTaskInfo])
        worker[kTaskInfo].<span class="hljs-title function_">done</span>(err, <span class="hljs-literal">null</span>);
      <span class="hljs-keyword">else</span>
        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
      <span class="hljs-comment">// Remove the worker from the list and start a new Worker to replace the</span>
      <span class="hljs-comment">// current one.</span>
      <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>);
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
    });
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">push</span>(worker);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
  }

  <span class="hljs-title function_">runTask</span>(<span class="hljs-params">task, callback</span>) {
    <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>) {
      <span class="hljs-comment">// No free threads, wait until a worker thread becomes free.</span>
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">push</span>({ task, callback });
      <span class="hljs-keyword">return</span>;
    }

    <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>();
    worker[kTaskInfo] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span>(callback);
    worker.<span class="hljs-title function_">postMessage</span>(task);
  }

  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
    <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>();
  }
}

<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>
<p>Without the explicit tracking added by the <code>WorkerPoolTaskInfo</code> objects,
it would appear that the callbacks are associated with the individual <code>Worker</code>
objects. However, the creation of the <code>Worker</code>s is not associated with the
creation of the tasks and does not provide information about when tasks
were scheduled.</p>
<p>This pool could be used as follows:</p>

<pre class="with-47-chars"><input class="js-flavor-toggle" 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>;
<span class="hljs-keyword">import</span> os <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;

<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>());

<span class="hljs-keyword">let</span> finished = <span class="hljs-number">0</span>;
<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++) {
  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> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i, err, result);
    <span class="hljs-keyword">if</span> (++finished === <span class="hljs-number">10</span>)
      pool.<span class="hljs-title function_">close</span>();
  });
}</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>);
<span class="hljs-keyword">const</span> os = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>);

<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>());

<span class="hljs-keyword">let</span> finished = <span class="hljs-number">0</span>;
<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++) {
  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> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i, err, result);
    <span class="hljs-keyword">if</span> (++finished === <span class="hljs-number">10</span>)
      pool.<span class="hljs-title function_">close</span>();
  });
}</code><button class="copy-button">copy</button></pre>
<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>
<p>Event listeners triggered by an <a href="events.html#class-eventemitter"><code>EventEmitter</code></a> may be run in a different
execution context than the one that was active when <code>eventEmitter.on()</code> was
called.</p>
<p>The following example shows how to use the <code>AsyncResource</code> class to properly
associate an event listener with the correct execution context. The same
approach can be applied to a <a href="stream.html#stream"><code>Stream</code></a> or a similar event-driven class.</p>

<pre class="with-72-chars"><input class="js-flavor-toggle" 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>;
<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>;

<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> {
  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> {
    <span class="hljs-comment">// Execution context is bound to the current outer scope.</span>
  }));
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-comment">// Execution context is bound to the scope that caused 'close' to emit.</span>
  });
  res.<span class="hljs-title function_">end</span>();
}).<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>);
<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>);

<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> {
  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> {
    <span class="hljs-comment">// Execution context is bound to the current outer scope.</span>
  }));
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-comment">// Execution context is bound to the scope that caused 'close' to emit.</span>
  });
  res.<span class="hljs-title function_">end</span>();
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre></section>
        <!-- API END -->
      </div>
    </div>
  </div>
</body>
</html>