【发布时间】:2018-02-08 13:23:25
【问题描述】:
我们如何从传递给事件发射器的回调中结束 async 函数而不承诺事件发射器?
同样不使用外部模块,只需简单的NodeJS 7.x/8.x(支持Es6语法和async/await。
我们希望基本上将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; ?
});
}
免责声明
如果这个问题已经在某个地方完成,我想道歉。所做的研究显示了与混合异步与同步逻辑相关的问题,但我对此一无所知。
标题中类似的问题是this 'write async function with EventEmitter',但与本问题无关。
【问题讨论】:
-
不,使用
async/await是不可能的,而不承诺你正在等待的东西。 -
太糟糕了,谢谢!这就是我想知道的。所以我想我将开始编写一个特定于域的承诺者 o 从事件发射器返回承诺......
标签: javascript node.js asynchronous