Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
ronkorving opened this issue Oct 10, 2018 · 2 comments
Closed

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

ronkorving opened this issue Oct 10, 2018 · 2 comments

Comments

@ronkorving
Copy link
Contributor

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.

@mscdex
Copy link
Contributor

mscdex commented Oct 10, 2018

See this PR.

@ronkorving
Copy link
Contributor Author

@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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants