Day 23 of 30 of JavaScript
Tags: webdev, javascript, beginners, tutorial
Published: 2024-06-28 11:49:49

Hey reader👋 Hope you are doing well😊
In the last post we have talked about Callbacks. In this post we are going to discuss about Promises.
So let's get started🔥

## Promises

Promises are used to handle Asynchronous Operations preventing callback hell and unmanageable code. A Promise is an object that will produce a single value some time in the future. If the promise is successful, it will produce a resolved value, but if something goes wrong then it will produce a reason why the promise failed.
It is something like when you make a promise either you fullfill it or tell your reasons why you didn't able to fullfill it. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02f4kczp8o1ah5jd0alq.png)
So this is an example of Promise. If the condition is true `resolve` method is called else `reject()` method is called. If promise is fullfilled then "success" is printed else an error is caught.
Note that we `resolve` method is utilized in `.then` and `reject` in `.catch`.

## How to create a Promise?

To create a promise, you need to create an instance object using the Promise constructor function. The Promise constructor function takes in one parameter. That parameter is a function that defines when to resolve the new promise, and optionally when to reject it.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hkl980zg41ei0d8ktbpw.png)
In promises, resolve is a function with an optional parameter representing the resolved value. Also, reject is a function with an optional parameter representing the reason why the promise failed.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s2jyc9om9n8tvbyd1k5g.png)

## States of Promise

- pending: This is the default state of a defined promise

- fulfilled:  This is the state of a successful promise

- rejected: This is the state of a failed promise

## Callback in Promises

To use a callback in Promise we need to use `.then` method. This method takes in two callback functions. The first function runs if the promise is resolved, while the second function runs if the promise is rejected. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02f4kczp8o1ah5jd0alq.png)

## How Promises eliminate Callback hell

Promises are a good way to eleminate callback hell as they use `.then()` which returns a promise either fullfilled or rejected hence eliminating "Pyramid of Doom".
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ok3qmbksz5dbqvb5ss3g.png)
The above code will lead to Callback hell. Let's use Promise to resolve this issue.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xsxgu84gamcq9ku96xn4.png)
Now here you can see that we no more have callback syntax and whenever a promise fails we have a rejected promise and we will stop here to check for errors.
 
## Handle Errors in Promise

To handle errors in Promises, use the `.catch()` method. If anything goes wrong with any of our promises, this method can catch the reason for that error.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iz4rde8s0mqk5q0ssqo7.png)

## Handling multiple Promises at once

When we have multiple promises we can run all in parallel at once. The methods through which we can achieve this are -:

- `Promise.all()`
- `Promise.race()`
- `Promise.any()`
- `Promise.allSettled()`

**`Promise.all()`**
`Promise.all()` accepts an array of promises as an argument but returns a single promise as the output.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cree45p3ijktwp8jqyma.png)
The single promise returns resolves with an array of values if all the promises in the input array are fulfilled.If at least one promise in the input array does not resolve, `Promise.all()` will return a rejected promise with a reason. The reason of rejection will be same as the promise that is rejected.
`Promise.all()` will run all the input promises before it returns a value. But it does not run the promises one after the other–instead it runs them at the same time.
This is why the total time it would take Promise.all() to return a value is roughly the time it would take the longest promise in the array to finish.

`**Promise.race()**`
`Promise.race()` returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j0fxzykqv42q9nm28llv.png)
Here as first promise is resolving fastly that is why first is printed.
If the promise with the shortest execution time happens to be rejected with a reason, `Promise.race()` returns a rejected promise and the reason why the fastest promise was rejected.

`**Promise.any()**`
`Promise.any()` accepts an array of Promises as an argument but returns a single Promise as the output. The single promise it returns is the first resolved promise in the input array. This method waits for any promise in the array to be resolved and would immediately return it as the output.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihet5tp5oan018vsojnv.png)
If none of the promises in the array are resolved, `Promise.any()` returns a rejected promise. This rejected promise contains a JavaScript array of reasons, where each reason corresponds with that of a promise from the input array.

**`Promise.allSettled()`**
`Promise.allSettled()` is used when we want to wait for all promises to complete regardless of whether they are fulfilled or rejected.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ymqb2fjddb99ea1ftr7m.png)
`Promise.allSettled()` is similar to `Promise.all()` in that all their input promises must settle before the promise they return has a settled state—fulfilled or rejected.
The difference is `Promise.all()` can only be successful if all the promises in the input are resolved, while `Promise.allSettled()` does not care about the status of the input promises.

So this was all about Promises. Now you have better understanding of Promises. In the next blog we will discuss about `Async/Await`. Till then stay connected and follow me.
Thankyou 🩵