@@ -507,7 +507,7 @@ createHook({
507
507
}
508
508
}).enable ();
509
509
510
- const server = createServer (function (req , res ) {
510
+ const server = createServer ((req , res ) => {
511
511
executionAsyncResource ()[sym] = { state: req .url };
512
512
setTimeout (function () {
513
513
res .end (JSON .stringify (executionAsyncResource ()[sym]));
@@ -862,6 +862,31 @@ for (let i = 0; i < 10; i++) {
862
862
}
863
863
```
864
864
865
+ ### Integrating ` AsyncResource ` with ` EventEmitter `
866
+
867
+ Event listeners triggered by an [ ` EventEmitter ` ] [ ] may be run in a different
868
+ execution context than the one that was active when ` eventEmitter.on() ` was
869
+ called.
870
+
871
+ The following example shows how to use the ` AsyncResource ` class to properly
872
+ associate an event listener with the correct execution context. The same
873
+ approach can be applied to a [ ` Stream ` ] [ ] or a similar event-driven class.
874
+
875
+ ``` js
876
+ const { createServer } = require (' http' );
877
+ const { AsyncResource , executionAsyncId } = require (' async_hooks' );
878
+
879
+ const server = createServer ((req , res ) => {
880
+ const asyncResource = new AsyncResource (' request' );
881
+ // The listener will always run in the execution context of `asyncResource`.
882
+ req .on (' close' , asyncResource .runInAsyncScope .bind (asyncResource, () => {
883
+ // Prints: true
884
+ console .log (asyncResource .asyncId () === executionAsyncId ());
885
+ }));
886
+ res .end ();
887
+ }).listen (3000 );
888
+ ```
889
+
865
890
## Class: ` AsyncLocalStorage `
866
891
<!-- YAML
867
892
added: v13.10.0
@@ -1100,8 +1125,10 @@ to associate the asynchronous operation with the correct execution context.
1100
1125
[ `destroy` callback ] : #async_hooks_destroy_asyncid
1101
1126
[ `init` callback ] : #async_hooks_init_asyncid_type_triggerasyncid_resource
1102
1127
[ `promiseResolve` callback ] : #async_hooks_promiseresolve_asyncid
1128
+ [ `EventEmitter` ] : events.html#events_class_eventemitter
1103
1129
[ Hook Callbacks ] : #async_hooks_hook_callbacks
1104
1130
[ PromiseHooks ] : https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit
1131
+ [ `Stream` ] : stream.html#stream_stream
1105
1132
[ `Worker` ] : worker_threads.html#worker_threads_class_worker
1106
1133
[ promise execution tracking ] : #async_hooks_promise_execution_tracking
1107
1134
[ `util.promisify()` ] : util.html#util_util_promisify_original
0 commit comments