- Promise.all(): it is used to handle multiple promises together. It takes an array of promises as input, and then it gives an array as output.
syntax : const [data1, data2, data3]=Promise.all([p1, p2, p3])
3s 1s 4s ===> it takes 4 seconds to fulfil the promise. all methods.
- promise.all will make all three API calls in parallel, but it will wait for all of them to finish, and then it will collect the result and it will give you this result.
Example :
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success...");
}, 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success...");
// reject("fail...");
}, 1000);
});
Promise.all([p1, p2]).then(([data, data2]) => console.log(data, data2)).catch((error)=>console.log(error));
//or
async function getData() {
const [data, data2] = await Promise.all([p1, p2]);
}
getData();
Failure case of Promise.all method:
- As soon as any of these promises are rejected, the promise.all methods will throw an error.
- It will quickly throw an error as soon as any promise fails, it will not wait for other promises.
Example :
Promise.all([p1, p2])
.then(([data, data2]) => console.log(data, data2))
.catch((error)=>console.log(error));
promise.allSettled() :
- it is the same as Promise.all methods, but it is different in Promise.all method failure cases.
- What if one of these promises gets rejected? It will wait for all promises to be fulfilled, whether any promises are rejected or fulfilled.
- the output of the rejected promise is an error.
example: const [data, error, data3]=Promise.allSettled([p1, p2, p3])
Promise.race() :
- It gives results quickly as soon as promises are fulfilled or rejected...
- Whatever promise is fulfilled or rejected first, you will get that result.
- It's kind of race first promises whatever is resolved in that array, whether it is success or failure. It will return the result.
================= settled =====================
Resolve -----> reject
Success -----> failure
Fulfilled -----> rejected