Skip to main content

Promise.allSettled

Promise.allSettled() takes an array of promises as input and returns an array with the result of all the promises whether they are rejected or resolved.

if (!Promise.myAllSettled) {
Promise.myAllSettled = function (promises) {
return Promise.all(
promises.map((promise) =>
Promise.resolve(promise)
.then((value) => ({ status: "fulfilled", value }))
.catch((reason) => ({ status: "rejected", reason }))
)
);
};
}

// Example usage:
const promises = [
Promise.resolve(42),
Promise.reject("error"),
new Promise((resolve) => setTimeout(resolve, 1000, "hello")),
];

Promise.myAllSettled(promises).then((results) => console.log(results));
// Output:
// [
// { status: 'fulfilled', value: 42 },
// { status: 'rejected', reason: 'error' },
// { status: 'fulfilled', value: 'hello' }
// ]