CKTIS / JavaScript
Promise.allSettled() result records
`Promise.allSettled()` fulfills with an array of outcomes in input order once all input promises have settled. Read each record’s `status` to decide whether to use `value` or `reason`.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
Promise.allSettled(iterable)
// Each element of the array that the returned promise fulfills with:
// { status: "fulfilled", value: … }
// { status: "rejected", reason: … }Promise.allSettled(iterable) is a static Promise method that takes a synchronous iterable, such as an array. It treats each entry as Promise.resolve() would: it adopts thenable outcomes and treats plain values as fulfillment values. Once every input promise is fulfilled or rejected, the returned promise fulfills with one outcome per entry, in iteration order rather than settlement order.
Promise.allSettled result records are ordinary JavaScript objects. A record with status: "fulfilled" has its own value property and no own reason property. A record with status: "rejected" has its own reason property and no own value property. Check status first: 0 and undefined can be valid fulfillment values, and a rejection reason need not be an Error and can also be undefined.
Unlike with Promise.all(), an individual rejection is recorded in the array and does not itself reject the aggregate promise. Use this when you want to keep successful results from independent tasks and handle failures separately. An error while reading the iterable can still reject the aggregate promise rather than produce an outcome record.
For empty input, the method returns a promise already fulfilled with [], but a .then() callback still runs asynchronously. For nonempty input, with standard promise behavior, the aggregate promise is still pending when returned, even if no input promise is pending. It can already be fulfilled on return, however, if the only input is a native promise that Promise.resolve() returns unchanged and whose own then method calls the fulfillment handler synchronously.
Examples
{
let finishFirst;
const first = new Promise((resolve) => { finishFirst = resolve; });
const second = Promise.reject("offline");
const batch = Promise.allSettled([first, second, 0]);
finishFirst("profile");
batch.then((results) => {
console.log(JSON.stringify(results));
for (const result of results) {
if (result.status === "fulfilled") {
console.log(`value: ${result.value}`);
} else {
console.log(`reason: ${result.reason}`);
}
}
});
}Result
[{"status":"fulfilled","value":"profile"},{"status":"rejected","reason":"offline"},{"status":"fulfilled","value":0}]
value: profile
reason: offline
value: 0The second promise rejects before the first one fulfills, but its record is still second. The plain value `0` produces a record with status `"fulfilled"`.
Related lessons
- JavaScript · Lesson 15 · Intermediate · Version: 3