We use Promise or async await to fetch API which is a good approach but it is best for when we have to make a single asynchronous operation, what about if I have to make multiple asynchronous operations like if I have to make fetch for multiple? Here Promise.all() comes into my mind.
So, Promise.all() is used for parallel API calling. This means that instead of calling API sequentially, we call API parallel, which speeds up asynchronous operations and reduces time by almost 34%. It is an efficient way to make multiple API calls.
How we use Promise.all
Promise.all takes promise in array.
So to implement this we should follow these steps.
- create a promising variable whose type should be an array []
- first make API calls in the loop or manually without awaiting which means we did not use await.
- now push each promise into the promise variable.
- Inside try catch use Promise.all(promise) with async await.
const promise = [];
for (let i = 0; i < 10; i++) {
const getPromise = fetch("https://catfact.ninja/fact", { method: "GET" });
console.log("making promises...");
promise.push(getPromise);
}
console.log("promise", promise);
const resolvePromise = async () => {
try {
const response = await Promise.all(promise);
console.log("response", response);
} catch (error) {
console.log("error", error);
}
};
resolvePromise();
But here Promise.all() return execution even one promise reject, that means after that all promises will not execute. but what about if I have to make all promises settled whether rejected or resolved so for this there is another method of Promise which is the best scenario which will be discussed below step by step.
However, there is another method that also exists in Promise to achieve parallel processing like allSettled(), any(), and race().
Now let's discuss them one by one.
Promise.allSettled(): It is used to settle all promises, whether resolved or rejected.
For example, we can use where we want to execute all promises whether it resolves or rejects it will execute all promises.Promise.any(): It is used to return only the first resolved promise which means it does not wait to resolve or reject all promises it returns or stops exec even only promises resolve. it will not give an error if any promise is rejected until and unless all promises are rejected if all promises are rejected then it only gives an aggregation error.
For example, we can use where we want the first resolved promise. because it simply ignores the rejection until all promises are rejected.Promise.race(): It returns the first settled promise whether it resolves or rejects does not depend.
Example: we can use this where we want the first result whether it resolves or is rejected does not depend.