HomeToolsAbout a20k

Parallel Promise

Promise.all()

Promise.all() is used for parallel fetch requests

const [response, categoryReponse] = await Promise.all([ fetch('/item'), fetch('/itemCategories') ]);

await Promise.all([...]) starts fetch requests in parallel, and waits until all of them are resolved

If any request fails, then the whole parallel promise gets rejected right away with the failed request error

More on Promise.all()

Takes an iterable of promises as input and returns a single Promise

const promise1 = Promise.resolve(3); const promise2 = 42; const promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 100, 'foo'); }); Promise.all([promise1, promise2, promise3]).then((values) => { console.log(values); }); // Expected output: Array [3, 42, "foo"]

Promise.all waits for all fulfillments (or the first rejection)

  • It fails fast
    • Meaning, if you have multiple iterable Promises still pending, but one of the earlier Promise resulted in reject, the Promises further down won't get resolved
const p1 = Promise.resolve(3); const p2 = 1337; const p3 = new Promise((resolve, reject) => { setTimeout(() => { resolve("foo"); }, 100); }); Promise.all([p1, p2, p3]).then((values) => { console.log(values); // [3, 1337, "foo"] });

Combining Async/Await with Promise.all()

async function fetchImages() { const promiseArray = [ fetch("imageUrl1"), fetch("imageUrl2"), fetch("imageUrl3") ]; await Promise.all(promiseArray) .then((data) => { setImageData(data); }) }

Promise.allSettled()

Similar to Promise.all(), returns a single Promise and takes in an interable of promises as inputs

  • This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise
const promise1 = Promise.resolve(3); const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'), ); const promises = [promise1, promise2]; Promise.allSettled(promises).then((results) => results.forEach((result) => console.log(result.status)), ); // Expected output: // "fulfilled" // "rejected"
© VincentVanKoh