将 AsyncResource 与 EventEmitter 集成
\Integrating AsyncResource with EventEmitter
由 EventEmitter 触发的事件监听器可能在与调用 eventEmitter.on() 时处于活动状态的执行上下文不同的执行上下文中运行。
\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.
以下示例显示如何使用 AsyncResource 类将事件监听器与正确的执行上下文正确关联。相同的方法可以应用于 Stream 或类似的事件驱动类。
\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.
import { createServer } from 'node:http'; import { AsyncResource, executionAsyncId } from 'node:async_hooks'; const server = createServer((req, res) => { req.on('close', AsyncResource.bind(() => { // Execution context is bound to the current outer scope. })); req.on('close', () => { // Execution context is bound to the scope that caused 'close' to emit. }); res.end(); }).listen(3000);const { createServer } = require('node:http'); const { AsyncResource, executionAsyncId } = require('node:async_hooks'); const server = createServer((req, res) => { req.on('close', AsyncResource.bind(() => { // Execution context is bound to the current outer scope. })); req.on('close', () => { // Execution context is bound to the scope that caused 'close' to emit. }); res.end(); }).listen(3000);