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