Skip to content

Promisified equivalent of EventEmitter.once() #20893

Description

@kirly-af

Hi,

Right now we can subscribe to one time events using .once(). Because most (all?) Node event emitters emit an "error" event when an error occurs, it seems reasonable to wrap such events in a Promise. For example:

const EventEmitter = require('events')
const myEmitter = new EventEmitter()

myEmitter.oncePromise('ready')
  .then(() => console.log('end event fired'))

myEmitter.emit('load')
myEmitter.emit('ready')

The name oncePromise is probably not the best but you get the idea.
Given the following implementation:

const EventEmitter = require('events')
EventEmitter.prototype.oncePromise = function(completeEvent, errorEvent = 'error') {
  return new Promise((resolve, reject) => {
    this.once(completeEvent, resolve).once(errorEvent, reject)
  })
}

That way we could leverage async/await flow and error handling:

const myEmitter = new EventEmitter()

function foo() {
  setTimeout(() => myEmitter.emit('error', new Error('foo')), 500)
}

function bar() {
  console.log('bar')
}

(async () => {
  try {
    foo()
    await myEmitter.oncePromise('ready')
    bar() // never gets called
  } catch (err) {
    console.log(err) // "foo"
  }
})()

Existing solutions:

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions