Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consume async iterable without variable declaration

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?

like image 745
jens1101 Avatar asked Sep 11 '26 09:09

jens1101


1 Answers

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.

Future solution

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'
like image 76
jens1101 Avatar answered Sep 13 '26 00:09

jens1101