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 to Symbol.iterator.

  • Method next() of an async iterator returns Promises for IteratorResults.

  • asynchronous version of the for-of loop: for-await-of:

async function f() {
  for await (const x of createAsyncIterable(["a", "b"])) {
    console.log(x);
  }
}
// Output:
// a
// b

It's pretty cool that for-await falls back to Symbol.iterator. It means you can use it with regular iterables like arrays:

async function example() {
  const arrayOfFetchPromises = [fetch("1.txt"), fetch("2.txt"), fetch("3.txt")];

  // Regular iterator:
  for (const item of arrayOfFetchPromises) {
    console.log(item); // Logs a promise
  }

  // Async iterator:
  for await (const item of arrayOfFetchPromises) {
    console.log(item); // Logs a response
  }
}

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