Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

for await...of

Loops over asynchronous data sources, waiting for each item.

Available since: ES2018

Syntax

for await (const item of asyncIterable) { … }

Examples

Looping over an array of promises:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
 
for await (const value of [wait(100, 'first'), wait(50, 'second')]) {
  console.log(value);
}

Output:

first
second

An async generator — data arrives in chunks:

async function* pages() {
  for (let page = 1; page <= 3; page++) {
    await new Promise((resolve) => setTimeout(resolve, 20));
    yield `page ${page}`;
  }
}
 
for await (const page of pages()) {
  console.log(page);
}

Output:

page 1
page 2
page 3

Notes

The order is kept: even if the second promise finishes first, it is printed second.

See also

  • for...of — Loops over the values of arrays, strings, Maps, Sets and other iterables.
  • await — Waits for a promise and returns its value.
  • function* — A generator function: produces values one at a time with yield.

Related recipes

In the tutorial

  • Iterators and generators — How for...of works in JavaScript: iterable objects, iterators and the next method, generator functions with yield, and your own iterable object.

Thanks for reading!

Donate to the site — we work hard for you.