🔰Promises in parallel
JS ⟩ async ⟩ Promise ⟩ in parallel
will reject immediately upon any of the input promises rejecting.
Promise.allSettled() (⭐️ ES2020)
will wait for all input promises to complete, regardless of whether or not one rejects.
will always return the final result of every promise and function from the input iterable. (order is preserved)
await promises (in parallel or in series)
// 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
)💾 replit:Promise.all()
// 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 }
});💾 replit:Promise.race()
// ⭐ 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'
});Promise.all() - rejected immediately if any rejetcted, fulfilled if all fulfilled.
Promise.allSettled() - a Promise that will always be fulfilled (with an array of outcome objects) when all settled.
Promise.race() - settled immediately if any is settled.
Last updated
Was this helpful?