Promises In JavaScript
Published: 2022-02-12 11:02:05


In JavaScript, promises are one of the techniques to deal with asynchronous actions. Many people have trouble understanding how Promises operate, so I'll try to define them as simply as possible in this post.
Because promises are such a broad topic,However, you'll discover an overview of Promises, as well as definitions of words like resolve, reject, and chaining, as well as a code example for constructing and using Promises.

## What is Promise
In JavaScript, a promise is equivalent to a promise in real life. When we make a promise in real life, we are guaranteeing that we will follow through on it. Promises can only be made in the future, after all.
A promise has two outcomes: it will either be maintained or will not be kept when the time arrives.
This is also true in JavaScript for promises. When we define a promise in JavaScript, it will either be resolved or refused when the time arrives.

## Promises In JavaScript
To begin with, a Promise is an object. The Promise object has three states:

1. Pending: Before the Promise succeeds or fails, it is in this state.
2. Resolved: Promise fulfilled
3. Rejected: Promises that were not kept

## Working Of Promises Process



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6jm0yh2sgud29rz663y.jpg)
When we use a Promise to request data from the server, it will be in pending status until we receive our data.
The Promise will be resolved successfully if we are able to obtain the information from the server. However, if we do not receive the information, the Promise will be rejected.
If there are many requests, a new process will start once the first Promise is resolved (or rejected), to which we can link it directly using a mechanism called chaining.

## What is Difference between Callbacks and Promises ?
The key difference between Callback Functions and Promises is that instead of providing a Promise, we attach a callback to it. So, with Promises, we still use callback functions, but in a different way (chaining).
This is one of the most compelling reasons to use Promises, but why?
## What is Chaining ?
For many years, JavaScript has relied solely on callback functions to perform asynchronous actions. However, in other circumstances, Promises may be a superior choice.
If we try to use good-old Callbacks for many async actions, we'll quickly find ourselves in a predicament known as Callback hell:
``` js
firstRequest(function(response) {  
    secondRequest(response, function(nextResponse) {    
        thirdRequest(nextResponse, function(finalResponse) {     
            console.log('Final response: ' + finalResponse);    
        }, failureCallback);  
    }, failureCallback);
}, failureCallback);
```
However, because we can attach Callbacks instead of forwarding them, the same code above looks more clearer and easier to comprehend when we handle the same task with Promises:
``` js
firstRequest()
  .then(function(response) {
    return secondRequest(response);
}).then(function(nextResponse) {  
    return thirdRequest(nextResponse);
}).then(function(finalResponse) {  
    console.log('Final response: ' + finalResponse);
}).catch(failureCallback);
```
The code above demonstrates how many callbacks can be linked together. Chaining is one of Promises' finest features.

## Creating and Using A Promise Step by Step
Firstly, we use a constructor to create a Promise object:
```js
const myPromise = new Promise();
```
It takes two parameters, one for success (resolve) and one for fail (reject):
```js
const myPromise = new Promise((resolve, reject) => {  
    // condition
});
```
Finally, there will be a condition. If the condition is met, the Promise will be resolved, otherwise it will be rejected:
``` js
const myPromise = new Promise((resolve, reject) => {  
    let condition;  
    
    if(condition is met) {    
        resolve('Promise is resolved successfully.');  
    } else {    
        reject('Promise is rejected');  
    }
});
```
We have created our first Promise, Now we are going to use it.
## then( ) for resolved Promises:
If you look at the image at the top of this page again, you'll notice that there are two cases: one for resolved promises and one for rejected promises. If the Promise is fulfilled (success case), then something will occur (depends on what we do with the successful Promise).
```js
myPromise.then();
```
The then( ) method is called after the Promise is resolved. Then we can determine what to do with the resolved Promise.

For example, let’s log the message to the console that we got from the Promise:
```js
myPromise.then((message) => {  
    console.log(message);
});
```
## Catch for rejected Promises:
The then() method, on the other hand, is reserved for Promises that have been resolved. What if the Promise doesn't come true? The catch() method must then be used.

Similarly, we use the then() technique. We may also add the catch() method straight after then():
```js
myPromise.then((message) => { 
    console.log(message);
}).catch((message) => { 
    console.log(message);
});
```
If the promise is rejected, it will be sent to the catch() method, which will display a different message on the console this time.

## Conclusion
So that's how we make a JavaScript Promise and use it for resolved and rejected cases.
This post is merely an introduction to Promises, and I hope you found it useful in understanding what they are and how to utilise them.😅