typestar

Concurrent promises in JavaScript

Running many async operations at once.

const urls = ["/api/a", "/api/b", "/api/c"];

async function loadAll() {
  const requests = urls.map((url) => fetch(url));
  const responses = await Promise.all(requests);
  return Promise.all(responses.map((r) => r.json()));
}

async function loadSafely() {
  const results = await Promise.allSettled(urls.map((u) => fetch(u)));
  return results.filter((r) => r.status === "fulfilled");
}

How it works

  1. Promise.all waits for every promise, failing fast.
  2. Mapping over urls starts all requests immediately.
  3. Promise.allSettled reports each outcome instead.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
379
Tokens
113
Three-star pace
95 tpm

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

Type this snippet

Step 4 of 5 in Promises, step 4 of 19 in Promises & async.

← Previous Next →