0

I have an async function that performs an action. I need to wait for that action to complete by listening to an EventEmitter event.

In the below example url is obtained in the new event of the maildev EventEmitter. We want to wait for a new mail in order to continue the async function.

maildev.on('new', callback(mail) { return mail.url })

(async () => {

    await send_semail();
    const url = await // Wait for maildev.on('new', callback(mail)) to be fired
    await visit(url);

})()
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
Slake
  • 2,080
  • 3
  • 25
  • 32

1 Answers1

2

The way one would go about getting a promise resolving callback is using the Promise constructor:

(async () => {
  await send_semail();
  const { url } = await new Promise(resolve => maildev.on('new', resolve));
  await visit(url);
})()

See this question and answer on how to do this more generally for any callback type.

Note that JavaScript function names are typically camelCased rather than snake_cased.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Thanks for the extra comment, this isn't returning the "mail or url". How to return datas beyond the promise? – Slake Apr 21 '18 at 10:49
  • You can `return` from an async function and then listen to it in another function. – Benjamin Gruenbaum Apr 21 '18 at 11:41
  • Doesn't URL get passed to `visit`? If it's not then maildev's `new` event doesn't return an object with a URL property. – Benjamin Gruenbaum Apr 21 '18 at 12:23
  • The 'new' event doesn't return an object with an URL property. I simplified the code. This 'new' event returns a "mail" object, which I was parsing inside the callback. Can you give a link to the doc for your code? I'll look how to add code in the callback to return what I want. – Slake Apr 21 '18 at 12:30
  • 1
    Then the object returned by the `await` is the object the `new` event returns - process it after the `await` to get the URL – Benjamin Gruenbaum Apr 21 '18 at 13:46
  • That isn't working, console.log( url ); displays "undefined", but the 'new' event returns an email (I verified with another code) – Slake Apr 24 '18 at 08:23