NodeJS 7:EventEmitter +等待/异步

我们如何才能async在传递给事件发射器的回调中结束函数 器 ?

另外,无需使用 外部模块 ,只需使用普通的 (支持 语法和async/await

我们基本上希望将an async function ...与事件发射器混合使用,以便在事件发射器发出信号时解析它end

另外请记住,在使用其他异步功能完成之前,我们不会从事件发射器开始await

如果我们有一个“新的Promise(…)”,我们将调用resolve();。头痛已经过去了,但是在“异步”中没有“解决”,而且我们不能使用“返回”,因为我们在回调内部。

/*

* 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; ?

});

}

回答:

如果这个问题已经在某处完成,我想道歉。完成的研究显示了与异步与同步逻辑混合有关的问题,但是我对此一无所获。

回答:

我们可以在不向事件发射器承诺的情况下结束传递给事件发射器的回调的异步函数吗?

async/ await语法只是then调用的糖,它依赖于promise。

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 >:)');

}

以上是 NodeJS 7:EventEmitter +等待/异步 的全部内容, 来源链接: utcz.com/qa/411271.html

回到顶部