From fdaf0ca550098ff01c8ef9a29404aa2b53137721 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 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/33751 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Robert Nagy Reviewed-By: James M Snell Reviewed-By: Denys Otrishko Reviewed-By: Gerhard Stöbich Reviewed-By: Stephen Belanger Reviewed-By: Vladimir de Turckheim --- 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 1534ca853611f9..cdac6287f4d6e6 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -507,7 +507,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])); @@ -862,6 +862,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`