Promise in JavaScript | Useful Promise Methods: the last chapter
Understanding JavaScript();
every story has an end 😞 and so has this, this is the last chapter of promises in javascript.
if you have not read the other chapters of promises, here’s part 1 📗 of the story and here’s part 2. 📘
in this last chapter, we will learn a few useful methods of promises, Promise.all(), Promise.allSettled(), Promise.any() and Promise.race().
so let’s not waste a bit of time and get started.
Some Useful Promise Methods
Let’s consider the scenario where we are loading a social media application page where we need some data about the user, like the user’s friend list, the list of posts which was liked by the user and the list of the posts made by the user.
let’s create some promises namely userFriends, userLikes and userPosts.
Note: we are using the setTimeout function to mimic the API call, also please don’t mind the messages/returned data, that was just for fun😅.
userFriends is a promise which will have the user’s friends’, userLikes is a promise which will have the list of the posts which were liked by the user and the userPosts is a promise which will have the list of the posts made by the user.
you can implement the above scenario using callback and promise chaining also.
you might be thinking why this guy is giving useless Gyan(knowledge) 😠
No knowledge is ever wasted
we can simply make 3 different variables and try to resolve the promise no? ya sure if you don’t have any issues with writing a lot of extra code and not using the best practice, please go ahead.
Promise.all()
😶 okay, okay, please don’t get mad, I was just explaining that you can consume the promise in multiple ways 😅
here's the solution to it 😎.
we can use .all() method provided by the promise API, it will help us to consume multiple promises at the same time.
How it works
- It takes the iterable of promises.
example: Promise.all([promise1, promise2, promise3])
- Promise.all() method will return a single promise, the returned promise gets fulfilled when all the promises are fulfilled, and it will return the value of fulfilled promises in the same order as the promises were consumed
[promise1_output, promise2_output, promise3_output]
. - IMP if any promise gets rejected, promise.all() will get rejected with the first failure message.
- for example, if there is some error in fetching the post
uncaught (in promise) error fetching posts
- in this example, there are three promises getting consumed, let’s assume p1 gets completed in 2 seconds, p2 gets completed in 1 second and p3 gets completed in 3 seconds, the max time Promise.all() needs to consume all the promises is just ~3 seconds.
- because all the promises are consumed parallelly.
- in ~3 seconds all the promises will get consumed and the output value will be in front of you. will it make the process fast? yes of course.
Promise.allSettled()
- Promise.all() and Promise.allSettled() are nearly the same, Promise.allSettled() comes with some extra benefits.
- this method is used to consume multiple promises at the same time like Promise.all()
- but there is a slight difference here. let’s understand the difference by knowing how it works.
How it works
- it takes the iterable of promises.
example: Promise.all([promise1, promise2, promise3])
- the above screenshot is the output of the method Promise.allSettled().
- here comes the major difference between Promise.all() and Promise.allSettled()
- when we consume the promise we get the array of objects.
- each object is loaded with two keys status and value/reason.
- status contains the status of the promise (pending | fulfilled | rejected), read more about the promise state here.
- value contains the output of the promise. and if the promise gets rejected for any reason the error message that is returned by the promise will be stored in the reason key.
- so if any of the promises get rejected while getting consumed, Promise.all() will show that particular promise as rejected and another promise will not get affected by it.
- IMP: this doesn’t block your operation if any promise gets rejected.
- rejected promise will have the status rejected and the reason for the rejection.
- other promises will have the status as fulfilled and the output of the promise will be in the values key.
Promise.all() and Promise.allSettled() are helpful methods when it comes to the case where you need to consume multiple promises at the same time, the usage of both depends on the scenario in which you are using the method.
We will take a stock market example to understand the concept of the .any() and .race() methods provided by Promise API.
assume you are building a system that helps you analyze the charts, for that you need the data for every single second of the index or a stock.
so you thought of using the APIs from multiple service providers(assume three service providers) as you don’t want to take any risk, you will make a call to all three service providers at the same time and use the output of the provider who responds first.
Promise.any()
How it works
- as the method name suggests “it will return any one of the promises provided in the iterable”.
- okay making it simple, this method takes an iterable
Promise.any([provider1, provider2, provider3])
- and it returns a single promise when the returned promise is consumed it will return the value of the promise whose execution is completed first (among three service providers).
- IMP: rejected promises are ignored, if the fastest consumed promise status is rejected it will get ignored and the next successful promise value will be returned.
Promise.race()
How it works
- as the method name suggests “it will return any one of the promises provided in the iterable”.
- okay making it simple, this method takes an iterable
Promise.any([provider1, provider2, provider3])
- and it returns a single promise when the returned promise is consumed it will return the value of the promise whose execution is completed first (among three service providers).
- IMP: rejected promises are not ignored, if the fastest consumed promise status is rejected it will get ignored and the next successful promise value will be returned.
- the output of Promise.race() when the first returned promise is fulfilled.
- the output of Promise.race() when the first returned promise is rejected.
so ya, this is all about the promise, hope you enjoyed the read but only enjoying is not enough, get your hands dirty with the code, let me know if you are facing difficulty understanding any of the above concepts.