diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md index 7d6bd72e7de1fa..9978070eba51a7 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -509,7 +509,7 @@ createHook({ } }).enable(); -const server = createServer(function(req, res) { +const server = createServer((req, res) => { executionAsyncResource()[sym] = { state: req.url }; setTimeout(function() { res.end(JSON.stringify(executionAsyncResource()[sym])); @@ -864,6 +864,31 @@ for (let i = 0; i < 10; i++) { } ``` +### Integrating `AsyncResource` with `EventEmitter` + +Event listeners triggered by an [`EventEmitter`][] may be run in a different +execution context than the one that was active when `eventEmitter.on()` was +called. + +The following example shows how to use the `AsyncResource` class to properly +associate an event listener with the correct execution context. The same +approach can be applied to a [`Stream`][] or a similar event-driven class. + +```js +const { createServer } = require('http'); +const { AsyncResource, executionAsyncId } = require('async_hooks'); + +const server = createServer((req, res) => { + const asyncResource = new AsyncResource('request'); + // The listener will always run in the execution context of `asyncResource`. + req.on('close', asyncResource.runInAsyncScope.bind(asyncResource, () => { + // Prints: true + console.log(asyncResource.asyncId() === executionAsyncId()); + })); + res.end(); +}).listen(3000); +``` + ## Class: `AsyncLocalStorage`