@@ -507,7 +507,7 @@ createHook({
507507  }
508508}).enable ();
509509
510- const  server  =  createServer (function (req , res ) {
510+ const  server  =  createServer ((req , res )  =>  {
511511  executionAsyncResource ()[sym] =  { state:  req .url  };
512512  setTimeout (function () {
513513    res .end (JSON .stringify (executionAsyncResource ()[sym]));
@@ -862,6 +862,31 @@ for (let i = 0; i < 10; i++) {
862862}
863863``` 
864864
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+ 
865890## Class: ` AsyncLocalStorage `   
866891<!--  YAML
867892added: v13.10.0 
@@ -1100,8 +1125,10 @@ to associate the asynchronous operation with the correct execution context.
11001125[ `destroy` callback ] : #async_hooks_destroy_asyncid 
11011126[ `init` callback ] : #async_hooks_init_asyncid_type_triggerasyncid_resource 
11021127[ `promiseResolve` callback ] : #async_hooks_promiseresolve_asyncid 
1128+ [ `EventEmitter` ] : events.html#events_class_eventemitter 
11031129[ Hook Callbacks ] : #async_hooks_hook_callbacks 
11041130[ PromiseHooks ] : https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit 
1131+ [ `Stream` ] : stream.html#stream_stream 
11051132[ `Worker` ] : worker_threads.html#worker_threads_class_worker 
11061133[ promise execution tracking ] : #async_hooks_promise_execution_tracking 
11071134[ `util.promisify()` ] : util.html#util_util_promisify_original 
0 commit comments