Skip to content

Integrate AsyncLocalStorage with EventEmitter #33723

Closed
@puzpuzpuz

Description

@puzpuzpuz

Is your feature request related to a problem? Please describe.

I'm going to port this library to AsyncLocalStorage. As a part of this migration I need to make ALS play nicely with events emitted by request and response objects. Current version of the library uses ns.bindEmitter() method available in cls-hooked (it's also present in continuation-local-storage).

Describe the solution you'd like

It's enough to add .bindEmitter(emitter, store) method into ALS:

const store = { foo: 'bar' };
als.bindEmitter(req, store);

req.on('close', () => {
  console.log(als.getStore()); // prints "{ foo: 'bar' }"
});

Describe alternatives you've considered

Of course, this integration can be implemented as a user-land module. But I believe that this will be a common case among ALS users, so it's probably worth to consider integrating ALS with EventEmitter in the core.

As more of such changes can bloat ALS API, I'd like to hear opinions from @nodejs/async_hooks before starting to work on the implementation.

Update. The consensus is to add something like AsyncResource#bind() method that would allow to do the following:

als.run({ foo: 'bar' }, () => {
  AsyncResource res = new AsyncResource('foobar');
  req.on('close', res.bind(() => {
    console.log(als.getStore()); // prints "{ foo: 'bar' }"
  }));
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    async_hooksIssues and PRs related to the async hooks subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions