With a synchronous JavaScript generator I can iterate over it as follows:
(() => {
function * syncGenerator () {
yield 1
yield 2
yield 3
console.log('done')
}
Array.from(syncGenerator())
})()
This will simply iterate over the whole generator without having to initialise a variable. I would like to do the same with async generators. The closest solution I could come up with is as follows:
(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()) {}
})()
Unfortunately I had to instantiate the variable num in the above code snippet. This causes StandardJS to give an error on that line, because the variable isn't used. Is there any way I can iterate over an async generator without having to create a variable?
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.
Once the Iterator Helpers proposal matures and becomes available one could do something like the following for both synchronous and asynchronous generators:
function * syncGenerator () {
yield 1
yield 2
yield 3
console.log('sync done')
}
syncGenerator().forEach(() => {}) // Logs 'sync done'
async function * asyncGenerator () {
yield Promise.resolve(1)
yield Promise.resolve(2)
yield Promise.resolve(3)
console.log('async done')
}
asyncGenerator().forEach(() => {}) // Logs 'async done'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With