typestar

for await in JavaScript

Consuming an async iterable, one awaited value at a time.

async function* pages(total) {
  for (let page = 1; page <= total; page += 1) {
    await new Promise((resolve) => setTimeout(resolve, 1));
    yield { page, rows: page * 2 };
  }
}

async function main() {
  let rows = 0;
  for await (const page of pages(3)) {
    rows += page.rows;
  }
  console.log("rows:", rows);

  for await (const page of pages(5)) {
    if (page.page === 2) break;
    console.log("saw page", page.page);
  }

  const all = [];
  for await (const value of [Promise.resolve(1), Promise.resolve(2)]) {
    all.push(value);
  }
  console.log(all);
}

main();

How it works

  1. An async generator yields promises the loop awaits for you.
  2. Symbol.asyncIterator is the protocol behind it.
  3. Breaking out calls the generator's return, so cleanup runs.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
533
Tokens
175
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 1 of 2 in Iterating asynchronously, step 10 of 19 in Promises & async.

← Previous Next →