@@ -512,7 +512,7 @@ createHook({
512512 }
513513}).enable();
514514
515- const server = createServer(function (req, res) {
515+ const server = createServer((req, res) => {
516516 executionAsyncResource()[sym] = { state: req.url };
517517 setTimeout(function() {
518518 res.end(JSON.stringify(executionAsyncResource()[sym]));
@@ -867,6 +867,31 @@ for (let i = 0; i < 10; i++) {
867867}
868868```
869869
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+
870895## Class: `AsyncLocalStorage`
871896<!-- YAML
872897added: v12.17.0
@@ -1105,8 +1130,10 @@ to associate the asynchronous operation with the correct execution context.
11051130[`destroy` callback]: #async_hooks_destroy_asyncid
11061131[`init` callback]: #async_hooks_init_asyncid_type_triggerasyncid_resource
11071132[`promiseResolve` callback]: #async_hooks_promiseresolve_asyncid
1133+ [`EventEmitter`]: events.html#events_class_eventemitter
11081134[Hook Callbacks]: #async_hooks_hook_callbacks
11091135[PromiseHooks]: https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit
1136+ [`Stream`]: stream.html#stream_stream
11101137[`Worker`]: worker_threads.html#worker_threads_class_worker
11111138[promise execution tracking]: #async_hooks_promise_execution_tracking
11121139[`util.promisify()`]: util.html#util_util_promisify_original
0 commit comments