Skip to content

rfc: await emitter.once('event') #23399

Closed

Description

@ronkorving

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

When in an async/await heavy project, EventEmitter can sometimes get a little in the way of a super smooth developer experience.

I would like to make this type of scenario simpler:

async setup() {
  const server = http.createServer((req, res) => {});

  return new Promise((resolve, reject) => {
    server.listen();
    server.on('listening', () => {
      resolve();
    });
  });
}

There are 2 problems here:

  1. I have to manually set up a Promise.
  2. If in the middle of the listening event handler, an exception is thrown, it will be an unhandled one.

Describe the solution you'd like

listening is an event you only care about once, so it would be nice to have emitter.once() like behavior but for promises.

async setup() {
  const server = http.createServer((req, res) => {});
  server.listen();
  await server.once('listening');
}

I could image that the array of arguments sent to event listeners is also returned:

const [foo, bar] = await emitter.once('done');

Re-using the once method for this would avoid introducing a new method name that could conflict with existing emitters.

Please don't focus on the listening use-case too much, it is just one example (and this is not stackoverflow). It's the code pattern that I would like to discuss.

I would love to get peoples' input on this. Is this something you would want to see too? Or not, and why not? Is there a more elegant solution you can think of? Thanks.

Activity

  1. mscdex commented on Oct 10, 2018

    @mscdex
    Contributor

    See this PR.

  2. ronkorving commented on Oct 10, 2018

    @ronkorving
    ContributorAuthor

    @mscdex Oh my, how did I miss that? That's exactly what I was proposing. Thanks for sharing, I will close this issue.

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