使用同步的JavaScript生成器,我可以对其进行如下迭代:
(() => {
function * syncGenerator () {
yield 1
yield 2
yield 3
console.log('done')
}
Array.from(syncGenerator())
})()
这将简单地遍历整个生成器,而无需初始化变量。我想对异步生成器做同样的事情。我能想到的最接近的解决方案如下:
(async () => {
async function * asyncGenerator () {
yield Promise.resolve(1)
yield Promise.resolve(2)
yield Promise.resolve(3)
console.log('done')
}
for await (const num of asyncGenerator()) {}
})()
不幸的是,我不得不在上面的代码片段中实例化变量num
。这将导致StandardJS在该行上给出错误,因为未使用该变量。有什么方法可以遍历异步生成器而不必创建变量?
答案 0 :(得分:0)
根据对问题的评论和我自己的研究,在撰写本文时,我对问题的首选解决方案如下:
(async () => {
async function * asyncGenerator () {
yield Promise.resolve(1)
yield Promise.resolve(2)
yield Promise.resolve(3)
console.log('done')
}
// eslint-disable-next-line no-unused-vars
for await (const num of asyncGenerator()) {}
})()
请注意// eslint-disable-next-line no-unused-vars
注释,该注释禁止StandardJS为该行生成的警告。
Iterator Helpers提案一旦成熟并可用,就可以对同步和异步生成器执行以下操作:
function * syncGenerator () {
yield 1
yield 2
yield 3
console.log('sync done')
}
syncGenerator().toArray() // Logs 'sync done'
async function * asyncGenerator () {
yield Promise.resolve(1)
yield Promise.resolve(2)
yield Promise.resolve(3)
console.log('async done')
}
asyncGenerator().toArray() // Logs 'async done'