DEV Community

Nitesh Patel
Nitesh Patel

Posted on

Promise APIs with Example🤝

We know that promise is a special JavaScript object. It is a placeholder for a value which can be either fulfilled or rejected.

In this we will discuss how we can handle multiple promises.

1. Promises.all - It is used to handle multiple promises together. It takes array of promises as an input.

NOTE : You can take any iterable as input but as of now we are considering only array.

Example: promises.all([p1,p2,p3]) , where p1,p2,p3 are three different promises.
Suppose p1 takes 3sec , p2 takes 1sec and p3 takes 2sec time to complete.

case 1 : If all of three promises are fulfilled/success/resolve then output will be array of resolve value of all the three individual promises.

output : [val1,val2,val3]
where (val1,val2,val3 are object)

When the code executed, all the three promises will run parallelly but wait for all to finish. In our example , after 3sec output will be generated as p1 takes maximum time(3sec).

Case 2 : If any or all of the promises get rejected.

When code is executed and all promises run parallelly and as soon as any of promises get rejected, error will be thrown. The error will be same as error of that particular promise.

Suppose p2 get rejected while p1, p3 get resolved in the above example, then error will be thrown immediately after p2 is executed i.e. after 1sec.

2. Promise.allSettled

We have seen that if any of the promises get rejected then error is thrown, if we want result of other two promises whichever are resolved then we can use promise.allSettled

Example: promise.allSettled([p1,p2,p3]) , where p1,p2,p3 are three different promises.
Suppose p1 takes 3sec , p2 takes 1sec and p3 takes 2sec time to complete.

case 1 : If all promises get resolve then output will be array of resolve value of promise.

case2 : If any of promise get rejected.

Suppose p2 fails/rejected and p1, p3 get resolved then output will be array of return value of each promises. It doesn't matter if return value is error or success and it will wait for all the promises to settle.

NOTE : Promise.all is like fast failing and Promise.allSettled wait for settling promise then give result accordingly.

3. Promise.race

In this whichever promise get settled first, whether it is resolved or rejected, output is given accordingly. It doesn't wait for other promises to settle.

4. Promise.any

It is same as promise.race but the difference is that it will wait for first fullfilled/resolved/success promise result and then output is produced.

If all of the promises fails/rejected then output will be aggregate error.

Top comments (0)