JavaScript Promise.all and Friends
Promise.all waits for every promise in a list. Its friends allSettled, race, and any each wait in a different way.
Wait for every promise
Two timers finish at different times. Promise.all waits for both, then logs the results in list order.
const first = new Promise((resolve) => {
setTimeout(() => resolve("Bread"), 50);
});
const second = new Promise((resolve) => {
setTimeout(() => resolve("Milk"), 30);
});
Promise.all([first, second]).then((items) => console.log(items));Report every result
One promise fulfills and one rejects. Promise.allSettled waits for both and reports each result with its status.
const good = Promise.resolve("Bread");
const bad = new Promise((resolve, reject) => {
setTimeout(() => reject("No milk"), 50);
});
Promise.allSettled([good, bad]).then((results) => console.log(results));Take the first to finish
The faster timer wins the race. The slower promise keeps running, but the race already settled.
const slow = new Promise((resolve) => {
setTimeout(() => resolve("Slow"), 50);
});
const fast = new Promise((resolve) => {
setTimeout(() => resolve("Fast"), 30);
});
Promise.race([slow, fast]).then((winner) => console.log(winner));Take the first success
The first promise rejects, but Promise.any skips it. The second promise fulfills, so any fulfills with its value.
const broken = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Down")), 20);
});
const working = new Promise((resolve) => {
setTimeout(() => resolve("Up"), 50);
});
Promise.any([broken, working]).then((value) => console.log(value));Example
function load(name, ms) {
return new Promise((resolve) => {
setTimeout(() => resolve(name), ms);
});
}
Promise.all([load("Users", 50), load("Posts", 30), load("Photos", 40)])
.then((parts) => console.log(parts));Key points
- Promise.all: a method that waits for every promise in a list
- Promise.all fulfills with a list of the results, in list order.
- Promise.allSettled: a method that waits for every promise and reports each result
- Promise.race: a method that settles with the first promise to settle
- Promise.any: a method that fulfills with the first promise to fulfill
- Promise.all rejects as soon as one promise rejects.
In this example, the load function builds a promise for one part of a page. All three loads start together. Promise.all waits for every load, then logs the three names in list order.
Note
Promise.any rejects only when every promise rejects.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which method waits for every promise and keeps list order?