title: NodeJS 7: EventEmitter + await/async
body: <p>How we can end an <code>async</code> function from a callback passed to an event emitter <strong>without promisifing the event emitter</strong>?</p>
  
  <p>Also without using <em>external modules</em>, just plain <strong>NodeJS 7.x/8.x</strong> (Which supports <strong>Es6</strong> syntax and <code>async/await</code>.</p>
  
  <p>We want basically to mix an <code>async function ...</code> with an event emitter, so that it resolves when the event emitter signals <code>end</code>.</p>
  
  <p>Also bear in mind that we won't start with the event emitter until done with some other async functions, using <code>await</code>.</p>
  
  <p>If we had a "new Promise(...)" we would call resolve(); and the headache would be over, but in 'async' there's no 'resolve', plus we cannot use 'return' because we're inside a callback.</p>
  
  <pre><code>/*
   * Example of mixing Events + async/await.
   */
  
  // Supose a random pomise'd function like:
  function canIHazACheezBurger () {
    return new Promise((resolve, reject) =&gt; {
      setTimeout(() =&gt; {
        resolve(Math.random() &gt; 0.5);
      }, 500 + Math.random() * 500)
    });
  }
  
  /**
   * Then, we want to mix an event emitter with this logic,
   * what we want is that this function resolves the promise
   * when the event emitter signals 'end' (for example).
   * Also bear in mind that we won't start with the event emitter
   * until done with the above function.
   * If I had a "new Promise(...)" I would call resolve(); and the
   * headache would be over, but in 'async' there's no 'resolve',
   * plus I cannot use 'return' because I'm inside a callback.
   */
  async function bakeMeSomeBurgers () {
    let canIHave = await canIHazACheezBurger();
    // Do something with the result, as an example.
    if (canIHave) {
      console.log('Hehe, you can have...');
    } else {
      console.log('NOPE');
    }
    // Here invoke our event emitter:
    let cook = new BurgerCooking('cheez');
    // Assume that is a normal event emitter, like for handling a download.
    cook.on('update', (percent) =&gt; {
      console.log(`The burger is ${percent}% done`);
    });
    // Here lies the problem:
    cook.on('end', () =&gt; {
      console.log('I\'ve finished the burger!');
      if (canIHave) {
        console.log('Here, take it :)');
      } else {
        console.log('Too bad you can\'t have it &gt;:)');
      }
      // So, now... What?
      // resolve(); ? nope
      // return; ?
    });
  }
  </code></pre>
  
  <h2>Disclaimer</h2>
  
  <p>I want to apologize if this question is already done somewhere. The research done shows questions related to mix async with sync logic, but I've found nothing about this.</p>
  
  <p>A similar question in title is <a href="https://stackoverflow.com/questions/17740988/write-async-function-with-eventemitter">this 'write async function with EventEmitter'</a> but it has nothing to do with this question.</p>