NodeJS 7: EventEmitter + await/async

后端 未结 1 1591
深忆病人
深忆病人 2020-12-14 11:14

How we can end an async function from a callback passed to an event emitter without promisifing the event emitter?

Also without using <

相关标签:
1条回答
  • 2020-12-14 12:02

    Can we end an async function from a callback passed to an event emitter without promisifing the event emitter?

    No. async/await syntax is just sugar for then calls and relies on promises.

    async function bakeMeSomeBurgers () {
      let canIHave = await canIHazACheezBurger();
      if (canIHave)
        console.log('Hehe, you can have...');
      else
        console.log('NOPE');
    
      // Here we create and await our promise:
      await new Promise((resolve, reject) => {
        // Here invoke our event emitter:
        let cook = new BurgerCooking('cheez');
        // a normal event callback:
        cook.on('update', percent => {
          console.log(`The burger is ${percent}% done`);
        });
        cook.on('end', resolve); // call resolve when its done
        cook.on('error', reject); // don't forget this
      });
    
      console.log('I\'ve finished the burger!');
      if (canIHave)
        console.log('Here, take it :)');
      else
        console.log('Too bad, you can\'t have it >:)');
    }
    
    0 讨论(0)
提交回复
热议问题