Current solution(当前解决方案)
Based on the comments to the question and my own research my preferred solution to the problem at the time of writing is the following:
(根据对问题的评论和我自己的研究,在撰写本文时,我对问题的首选解决方案如下:)
(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()) {} })()
Note the // eslint-disable-next-line no-unused-vars
comment which suppresses the warning generated by StandardJS for that one line.
(请注意// eslint-disable-next-line no-unused-vars
注释,该注释禁止StandardJS为该行生成的警告。)
Future solution(未来的解决方案)
Once the Iterator Helpers proposal matures and becomes available one could do something like the following for both synchronous and asynchronous generators:
(一旦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'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…