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
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)
reject
, the Promises
further down won't get resolvedconst 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"] });
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
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"