Asynchronous Iteration

Usable only inside an async function, the for await...of statement loops over sync and async iterables such as String, Array, Array-like objects (eg. arguments / NodeList), TypedArray, Map, Set and user-defined async/sync iterables.One important use case of asynchronous iteration is pagination, ie. downloading more resources (for the next page) through AJAX calls upon user's navigation.

Over iterables


const asyncIterable = {
  [Symbol.asyncIterator]() {
    return {
      i: 0,
      next() {
        if (this.i < 3) {
          return Promise.resolve({ value: this.i++, done: false });
        }
        return Promise.resolve({ done: true });
      }
    };
  }
};

(async function() {
  for await (let num of asyncIterable) {
    console.log(num);
  }
})();

0 1 2

Over generators


async function* asyncGenerator() {
  let i = 0;
  while (i < 3) {
    yield i++;
  }
}

(async function() {
  for await (let num of asyncGenerator()) {
    console.log(num);
  }
})();

0 1 2
Be aware of yielding rejected promises from sync generator. In such case for await...of throws when consuming rejected promise and DOESN'T CALL finally blocks within that generator. This can be undesireable if you need to free some allocated resources with try/finally.
function* generatorWithRejectedPromises() {
  try {
    yield 0;
    yield 1;
    yield Promise.resolve(2);
    yield Promise.reject(3);
    yield 4;
    throw 5;
  } finally {
    console.log('called finally')
  }
}

(async function() {
  try {
    for await (let num of generatorWithRejectedPromises()) {
      console.log(num);
    }
  } catch (e) {
    console.log('catched', e)
  }
})();

// compare with for-of loop:
try {
  for (let numOrPromise of generatorWithRejectedPromises()) {
    console.log(numOrPromise);
  }
} catch (e) {
  console.log('catched', e)
}

(async function() {
  try {
    for (let numOrPromise of generatorWithRejectedPromises()) {
      console.log(await numOrPromise);
    }
  } catch (e) {
    console.log('catched', e)
  }
})()

0 1 2 catched 3 0 1 Promise { 2 } Promise { 3 } 4 catched 5 called finally 0 1 2 catched 3 called finally

(reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/ Reference/Statements/for-await...of )