Hacker News new | ask | show | jobs
by elmigranto 3005 days ago
Can someone please explain why for…of needed to be specialized for its async form?

I get why async generators & iterators won't work with plain for…of, but don't get why following is invalid:

    for (const i of [1, 2, 3])
      await getThingAtIndex(i);
The very last example in the article uses similar code, but I feel iterating over array of promises misses the point (as opposed to actually receiving async iterator with `async next () {…}` via `Symbol.iterator`).

Or am I missing something here? Thanks.

2 comments

What you've written isn't invalid, it just does something different. Async iterators effectively yield awaitable promises instead of values.

Iterators, normally, are synchronous. Generators immediately yield control to whatever is consuming from it. An async iterator yields things that will eventually yield control.

The best example I can think of is disk IO. In Python you can iterate over a file handle, but in JS you can't (without blocking). Async iterators would enable this: each yielded promise would resolve with the next line of the file.

Edit: the spec is pretty interesting: https://github.com/tc39/proposal-async-iteration/blob/master...

Your example is equal to

  await getThingAtIndex(1)
  await getThingAtIndex(2)
  await getThingAtIndex(3)
whereas the async for loop is equivalent to

  await Promise.all([
    getThingAtIndex(1),
    getThingAtIndex(2),
    getThingAtIndex(3)
  ])
Your example is valid syntax, but it executes each call synchronously.
The article says `This feature adds a new “for-await-of” loop that allows us to call async functions that return promises (or Arrays with a bunch of promises) in a loop. The cool thing is that the loop waits for each Promise to resolve before doing to the next loop.`. which seems to be in contention with what you say.