Μετάβαση στο κύριο περιεχόμενο
← ⚡ JavaScript & the browser·Ενότητα C4 · Μάθημα 7
ΕργασίαUse Promise.all to wait for two Promise.resolve calls: Promise.resolve(2) and Promise.resolve(3). Destructure the result and log the sum (expect 5).

Promise.all + Promise.race + Promise.allSettled

100 XP8 min
Θεωρία

The three combinators that matter

// Wait for everything; reject on the first error.
const [user, posts, todos] = await Promise.all([
  fetch("/api/user"),
  fetch("/api/posts"),
  fetch("/api/todos"),
]);

// Wait for the first to settle (winner takes all). Use sparingly — usually for timeouts.
const winner = await Promise.race([
  fetch(slowUrl),
  new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 5000)),
]);

// Wait for ALL to settle. Each item is { status: "fulfilled", value } or { status: "rejected", reason }.
const results = await Promise.allSettled([
  fetch("/api/user"),
  fetch("/api/risky"),
]);

When each one fits

  • `Promise.all` — the default. Three parallel fetches needed before you can render. If ONE fails, the whole batch fails (other fetches still complete, but you don't read their values).
  • `Promise.race` — racing for first response. Real-world use: timeout. Replaced in 2023 by AbortSignal.timeout for fetch (C4-06).
  • `Promise.allSettled` — you need all results regardless of failures. Dashboard widgets, batch saves, "send to 5 services in parallel and tell me which ones succeeded."

The N+1 trap

// SLOW — N sequential requests
const users = [];
for (const id of userIds) {
  users.push(await fetch(`/api/user/${id}`).then(r => r.json()));
}

// FAST — N parallel requests
const users = await Promise.all(
  userIds.map(id => fetch(`/api/user/${id}`).then(r => r.json()))
);

Sequential is fine when each request depends on the previous one. Parallel is the default for independent fetches.

Don't go too parallel

If you launch 1,000 fetches at once you'll get rate-limited, exhaust your browser's connection pool, or DDoS your own backend. For >20 parallel calls, batch them (e.g. p-limit library, or fold them in chunks of 5-10).

🔒

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.