Promise.all Patterns
Run multiple promises in parallel and handle results.
Code
JavaScript
// Wait for all
const [a, b, c] = await Promise.all([
fetch("/api/a").then((r) => r.json()),
fetch("/api/b").then((r) => r.json()),
fetch("/api/c").then((r) => r.json())
]);
// Fail if any fails
Promise.all([p1, p2]).catch((err) => console.error(err));
// All settled (never rejects)
const results = await Promise.allSettled([p1, p2]);
results.forEach((r) => {
if (r.status === "fulfilled") console.log(r.value);
else console.error(r.reason);
});Line-by-line explanation
- 1.Promise.all resolves when all resolve; rejects on first reject.
- 2.Destructure in order of input array.
- 3.Promise.allSettled returns status for each.
Expected output
Array of resolved values