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