NodeJS 7:EventEmitter +等待/asynchronous

我们如何通过传递给事件发射器的callback来结束async函数, 而不会使事件发射器事件发生

也没有使用外部模块 ,只是简单的NodeJS 7.x / 8.x (它支持Es6语法和async/await

我们基本上要把一个async function ...和一个事件发射器混合在一起,以便在事件发射器信号end时解决。

另外请记住,我们不会以事件发射器开始,直到完成一些其他的asynchronous函数,使用await

如果我们有一个“新的承诺(…)”,我们将调用resolve(); 头痛会结束,但在“asynchronous”没有“决心”,再加上我们不能使用“回报”,因为我们在callback。

 /* * Example of mixing Events + async/await. */ // Supose a random pomise'd function like: function canIHazACheezBurger () { return new Promise((resolve, reject) => { setTimeout(() => { resolve(Math.random() > 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) => { console.log(`The burger is ${percent}% done`); }); // Here lies the problem: cook.on('end', () => { console.log('I\'ve finished the burger!'); if (canIHave) { console.log('Here, take it :)'); } else { console.log('Too bad you can\'t have it >:)'); } // So, now... What? // resolve(); ? nope // return; ? }); } 

放弃

如果这个问题已经在某个地方完成了,我想道歉。 所做的研究显示了与同步逻辑混合asynchronous相关的问题,但是我对此一无所知。

标题中的类似问题是“用EventEmitter写入asynchronous函数”,但与此问题无关。

我们可以通过传递给事件发射器的callback来结束asynchronous函数吗?

没有async / await语法只是糖, then调用,并依靠承诺。

 async function bakeMeSomeBurgers () { let canIHave = await canIHazACheezBurger(); if (canIHave) console.log('Hehe, you can have...'); else console.log('NOPE'); // Here we create an 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 >:)'); }