Promise.all and Promise.allSettled
Promise.all(iterable)
Promise.allSettled(iterable)
new Promise(executor)Wait for every input to fulfill, or collect every outcome, including rejections. A throw inside the executor rejects the new Promise.
| Parameter | Description |
|---|---|
iterable | An iterable of promises or thenable values. |
executor | A function that receives resolve and reject. If it throws synchronously, the Promise rejects with that error. |
Returns: A Promise. all() fulfills with an array of values. allSettled() fulfills with an array of { status, value } or { status, reason } objects.
- Handle all() with try/catch or .catch(). allSettled() does not throw just because one input rejected.
async function main() {
const thrown = new Promise(() => { throw new Error("boom"); });
console.log(await thrown.then(() => "ok", (error) => error.message));
console.log((await Promise.all([Promise.resolve(1), Promise.resolve(2)])).join(","));
const settled = await Promise.allSettled([
Promise.resolve("ok"),
Promise.reject(new Error("nope")),
]);
console.log(settled.map((item) => item.status).join(","));
try {
await Promise.all([Promise.resolve(1), Promise.reject(new Error("fail"))]);
} catch (error) {
console.log(error.message);
}
}
await main();Expected output
boom
1,2
fulfilled,rejected
failRelated: Promise.race