From f39ee7d24598fbdcb43adce69f786c6af3ed525a 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 b15f8cb92263de..d7182f43f45288 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -512,7 +512,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])); @@ -867,6 +867,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`