CodeBlanks Logo Icon CodeBlanks

await expressions

JavaScript course · Intermediate · Lesson 82/134

Learn to iterate async iterables with for await...of.

The for await...of loop

Sometimes a list produces promises and you want to wait for each in order. The for await...of loop walks async iterables and awaits each item.

async function processUrls(urls) {
  for await (const url of fetchEach(urls)) {
    console.log(url);
  }
}

This loop works only inside an async function. Each iteration resolves the next promise, so items are processed in order.

What is an async iterable?

An object is async iterable when it has a Symbol.asyncIterator method. That method returns a next() function; each next() call returns a promise. for await...of calls this machinery automatically.

const stream = {
  async *[Symbol.asyncIterator]() {
    yield 'a'; yield 'b';
  }
};
for await (const x of stream) { /* ... */ }

Async generators (async function*) are the most common source of async iterables.

Exercise Write an async loop

Write async function processUrls(urls). Inside it, use for await (const url of fetchEach(urls)) to walk each url and print it with console.log(url).

Show example solution
async function processUrls(urls) {
  for await (const url of fetchEach(urls)) {
    console.log(url);
  }
}

Test yourself

  1. When do you use for await...of?

    • To walk an object's properties
    • To await an array of promises in parallel
    • To reject a promise
    • To await an array of promises one by one
    Show answer

    To await an array of promises one by one — Correct! for await...of walks async iterables in order.

  2. Complete the for await loop

    async function processUrls(urls) {
      ____ (const url of fetchEach(urls)) {
        console.log(url);
      }
    }
    Show answer
    async function processUrls(urls) {
      for await (const url of fetchEach(urls)) {
        console.log(url);
      }
    }
  3. Match for await...of concepts

    for await (const x of s)
    walks an async iterable
    Symbol.asyncIterator
    the async iterator symbol
    async function*
    defines an async generator
    yield value
    produces a value asynchronously

All lessons in Intermediate