Copy // rejected if any of the input Promises are rejected,
// otherwise, fulfilled with an array of values of each Promise.
Promise .all (
// array of URLs -> array of Promises
urls .map (url => fetch (url) .then (response => response .text ())
) .then (
texts => handle (texts) // do something with array of strings
)
Copy // custom Promise
const promiseFoo = new Promise ((resolve , reject) => {
setTimeout (resolve , 2000 , 'foo' );
// ╰───╯ <---- parameter to `resolve`
});
// ⭐ Promise.all()
// - rejected if any is rejected
// - fulfilled (with array of values) if all are fulfilled
Promise .all ([
Promise .resolve ( 3 ) ,
42 , // non-Promise value is OK
promiseFoo
]) .then (values => {
console .log (values); // [ 3, 42, 'foo' ]
});
// ⭐ Promise.allSettled()
// - always fulfilled with array of outcomes (objects)
Promise .allSettled ([
Promise .resolve ( 1 ) ,
Promise .reject ( 'bad boy' ) ,
3 ,
]) .then (results => {
results .forEach (result => console .log (result));
// { status: 'fulfilled', value: 1 } // ⭐ with `value`
// { status: 'rejected' , reason: 'bad boy' } // ⭐ with `reason`
// { status: 'fulfilled', value: 3 }
});
Copy // ⭐ Promise.race()
// - settled immediately if any is settled.
Promise.race([
new Promise(resolve => setTimeout(resolve, 500, 'one')),
new Promise(resolve => setTimeout(resolve, 200, 'two')), // resolve faster
]).then(value => {
console.log(value); // 'two'
});