Skip to content

Add async emit methods to EventEmitter #18646

@matthewadams

Description

@matthewadams
  • Version:
    v8.9.4

  • Platform:
    Darwin pumba-5.local 17.4.0 Darwin Kernel Version 17.4.0: Sun Dec 17 09:19:54 PST 2017; root:xnu-4570.41.2~1/RELEASE_X86_64 x86_64

  • Subsystem:
    events

https://nodejs.org/api/events.html#events_asynchronous_vs_synchronous instructs users to cause asynchronous event execution in the event handlers by using setImmediate or process.nextTick, which means that, when using EventEmitter#emit, asynchronous event handling is left to clients, and the EventEmitter has no control over whether an event is handled asynchronously or synchronously. In cases where the EventEmitter is sensitive to performance, the EventEmitter itself can dictate the event emission is asynchronous via code similar to the following:

class MyClass extends EventEmitter {
  // ...
  doSomething() {
    process.nextTick(() => this.emit.bind(this).call('myEvent', {foo:'bar'}))
    // ...
  }
}

The emit line above could be replaced by something convenient like

this.emitNextTick('myEvent', {foo:'bar'})
// or
this.emitImmediate('myEvent', {foo:'bar'})

or, even more conveniently,

this.emitAsync('myEvent', {foo:'bar'})

which uses either setImmediate or process.nextTick according to the current environment.

Metadata

Metadata

Assignees

No one assigned

    Labels

    eventsIssues and PRs related to the events subsystem / EventEmitter.feature requestIssues that request new features to be added to Node.js.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions