08. Async Iteration
Asynchronous iteration works with data that is delivered asynchronously. For example, lines of text, read asynchronously from a file or an HTTP connection.
The proposal specifies a new protocol for iteration that works asynchronously:
Async iterables are marked via
Symbol.asyncIterator
if it's defined, otherwise it will fall back toSymbol.iterator
.Method
next()
of an async iterator returnsPromises
forIteratorResults
.asynchronous version of the
for-of
loop:for-await-of
:
It's pretty cool that for-await
falls back to Symbol.iterator
. It means you can use it with regular iterables like arrays:
for-await
will give you each value once asyncIterator.next()
resolves. Because this involves awaiting promises, other things can happen on the main thread during iteration. asyncIterator.next()
isn't called for the next item until your current iteration is complete. This means you'll always get the items in order, and iterations of your loop won't overlap.
Last updated
Was this helpful?