Hi everyone! It's just another week with all the days feeling similar as such. With time passing by observing and learning lots of new languages and technologies. Along with that strengthening, the core is much more important. Unless you make your base strong you won't be able to build higher. Let's make our Javascript base stronger with another core concept Promise.
Promise
A promise is an object that represents an eventual execution of an asynchronous function and its resulting value. A promise is an asynchronous method returning values like synchronous methods.
The promise is in one of the following states.
- Pending: initial state
- Rejected: operation failed
- Fulfilled: operation completed successfully
Like most of the other javascript objects Promise can be chained. Promise provides Promise.then(), Promise.catch() and Promise.finally() methods for handling exception condition.
As we are now aware of the Promise now let's look at some of the Promise methods.
Promise.all([promise1, promise2,...])
This method accepts an array of promises and waits until all of the passed promises is resolved or until the first promise is rejected. It returns an array of responses or reasons for rejection.
If all the promises are fulfilled then, the array of results of all fulfilled promises are returned.
If at least one promise fails then, the reason for rejection of the first promise is returned.
Promise.allSettled([promise1, promise2,...])
This method accepts an array of promises and waits until all of the passed promises are settled no matter whether they are resolved or rejected.
It returns an array of responses from all resolved promise or reasons for rejection along with Status.
For resolved promise object containing status as "fulfilled" along with the values are returned.
For rejected promise object containing status as "rejected" along with the reasons for rejection are returned.
allSettled() function do not need a catch() function for handling the rejected Promise. Since the allSettled() function waits for settlement of Promises and not the resolution or rejection of Promise.
Promise.race([promise1, promise2,...])
This method accepts an array of promises as input and returns the response from the first promise settled.
If the first promise to be settled is resolved then it returns data else it returns reason for rejection.
That's all for promise methods.
Happy Coding!
Top comments (2)
Explained in simple language. Thanks Ravina
Thanks for your words 😁