我们如何通过传递给事件发射器的回调结束 async
函数而不 promise 事件发射器?
也不使用外部模块,只是简单的NodeJS 7.x/8.x(支持Es6语法和async/等待
。
我们主要是想将 async function ...
与事件发射器混合,以便在事件发射器发出 end
信号时解析。
另请记住,在使用 await
完成一些其他异步函数之前,我们不会从事件发射器开始。
如果我们有一个“new Promise(...)”,我们会调用 resolve();头痛也就过去了,但是在“async”中没有“resolve”,而且我们不能使用“return”,因为我们在回调中。
/*
* 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; ?
});
}
免责声明
如果这个问题已经在某处完成,我想道歉。所做的研究显示了与混合异步和同步逻辑相关的问题,但我对此一无所知。
标题中的类似问题是 this 'write async function with EventEmitter'但与本题无关。
最佳答案
Can we end an async function from a callback passed to an event emitter without promisifing the event emitter?
否。 async
/await
语法只是 then
调用的糖分,并且依赖于 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 >:)');
}
关于javascript - Node 7 : EventEmitter + await/async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45967019/