From ed845b81a9623ce73eeba257db7ef187c42691c8 Mon Sep 17 00:00:00 2001 From: Andrey Pechkurov Date: Fri, 5 Jun 2020 16:55:01 +0300 Subject: [PATCH] doc: add snippet for AsyncResource and EE integration --- doc/api/async_hooks.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) 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`