by elmigranto · 8y ago · 0 comments
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.
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...
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.