|
|
|
|
|
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. |
|
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...