Skip to content

async_hooks: add bindToAsyncScope method to AsyncResource

Closes #33723 (closed)

Adds bindToAsyncScope() method to AsyncResource class. This method should be handy for AsyncLocalStorage users (and not only them). Say, it allows binding EE/stream listeners to the specific resource:

const { createServer } = require('http');
const { AsyncResource, executionAsyncId } = require('async_hooks');

const server = createServer(function(req, res) {
  const asyncResource = new AsyncResource('request');
  const asyncId = asyncResource.asyncId();
  // The listener will always run in the execution context of `asyncResource`.
  req.on('close', asyncResource.bindToAsyncScope(() => {
    console.log(executionAsyncId()); // Prints the value of `asyncId`.
  }));
  res.end();
}).listen(3000);

cc @nodejs/async_hooks

Checklist
  • make -j4 test (UNIX), or vcbuild test (Windows) passes
  • tests and/or benchmarks are included
  • documentation is changed or added
  • commit message follows commit guidelines

Merge request reports

Loading