Concurrent data loading
Several independent API requests are required before rendering a view.
JavaScript · Function
Promise.all() combines an iterable of promises or values into one promise. It fulfills with results in input order only when every item fulfills, and rejects as soon as an item rejects.
Promise.all() converts an iterable of values and promises into one promise. It fulfills only after every input fulfills, producing their results in input order; it rejects as soon as an input rejects, using that rejection reason.
Promise.all(iterable)| Name | Type | Description |
|---|---|---|
iterable | iterable | An iterable, such as an Array, whose items may be promises, thenables, or ordinary values. |
A Promise that fulfills with an array of values when all inputs fulfill, or rejects with the first rejection reason. An empty iterable produces an already-fulfilled promise.
const [user, settings] = await Promise.all([
fetch("/api/user").then((response) => response.json()),
fetch("/api/settings").then((response) => response.json()),
]);
console.log(user, settings);Both requests start before either result is awaited, and the destructured values retain the input order.
Several independent API requests are required before rendering a view.
Multiple asynchronous validations must all pass before continuing.
Several files or resources need to be fetched before processing a batch.
It returns a single promise that fulfills after all input items fulfill, with an array of results in input order. It rejects when any input rejects.
Follow-up: How does an empty iterable behave? It returns an already-fulfilled promise, unlike a non-empty iterable whose settlement is asynchronous.
The result array follows the order in which promises are supplied, not the order in which they finish. This lets callers safely destructure results according to the input layout.
Follow-up: What happens if inputs are already fulfilled? A non-empty iterable still settles asynchronously.
It is useful when several related asynchronous operations must all succeed before execution continues. The operations can be started together, reducing unnecessary sequential waiting.
Follow-up: When would Promise.allSettled() be preferable? Use it when every outcome matters even if some operations reject.
Promise.allSettled()Promise.any()Promise.race()Promise