我尝试使用babel来使用async generator的简洁语法(我陷入了node 8),我想知道如何将事件发射器清晰地转换为async generator。
到目前为止,我的代码看起来像这样:
const { EventEmitter } = require('events')
// defer fonction for resolving promises out of scope
const Defer = () => {
let resolve
let reject
let promise = new Promise((a, b) => {
resolve = a
reject = b
})
return {
promise,
reject,
resolve
}
}
// my iterator function
function readEvents(emitter, channel) {
const buffer = [Defer()]
let subId = 0
emitter.on(channel, x => {
const promise = buffer[subId]
subId++
buffer.push(Defer())
promise.resolve(x)
})
const gen = async function*() {
while (true) {
const val = await buffer[0].promise
buffer.shift()
subId--
yield val
}
}
return gen()
}
async function main () {
const emitter = new EventEmitter()
const iterator = readEvents(emitter, 'data')
// this part generates events
let i = 0
setInterval(() => {
emitter.emit('data', i++)
}, 1000)
// this part reads events
for await (let val of iterator) {
console.log(val)
}
}
main()
这很复杂 - 能不能简化一下?
resolve()
来简化它,而不是存储在中间数组中。例如:resolve: (r: TRecord) => void
、new Promise<TRecord>(r => resolve = r)
、yield await promise
。 - Klesun.on('result'
被调用两次会怎么样?我不确定那是否可能发生。 - mpen.on('error', err => { throw err; })
会抛出一个错误,无处捕获。 - jcayzac