🤞Understanding Promises in JavaScript🚀
Published: 2022-09-12 18:52:25

---
title: 🤞Understanding Promises in JavaScript🚀
published: true
date: 2022-08-18 12:03:55 UTC
tags: 
canonical_url: https://blog.sagarmedtiya.me/understanding-promises-in-javascript
---
![image](https://cdn.hashnode.com/res/hashnode/image/upload/v1661946186871/-9NO2hO-z.gif)
## What is a Promise🤞?

By the definition of MDN,

_The **Promise** object represents the eventual completion (or failure) of an asynchronous operation and its resulting value._

We know that JavaScript is a synchronous programming language but callback function makes it Asynchronous.

Let's understand promise by simple example, suppose you made a promise🤞 to yourself that you will wake up at sharp 5AM. But eventually, you don't know whether you will make it or not, that means either you are going to complete that promise or not.

## How it works?

The promises returns one of the 3 possible states:

- **Fullfilled:** You woke up at sharp 5AM.
- **Rejected:** You didn't wake up at 5AM.
- **Pending:** You don't know if you'll wake up or not.

A promise is **settled** if it's not pending means it has been resolved or rejected. After it has been settled there is no use of calling `resolve()` or `reject()`.

### Syntax📃

```
new Promise( (resolve, reject)=> { ... } );

```

**For example📃** ,

```
let wakePromise = true;
let wakeUp = new Promise((resolve, reject)=> {
    setTimeout(() => {
        if (wakePromise) {
        resolve('I woke up');
    } 
    else {
        reject('I didnt wake up'); }
    }, 5000);
});
console.log(wakeUp);

```

**Output:**

![Screenshot 2022-08-18 112212.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1660803125791/08uwsZYG_.png)After completion of 5 seconds the promise gets fulfilled.

![Screenshot 2022-08-18 113014.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1660803579001/4kDbX2CVl.png)

If we change `wakePromise = false` then it returns,

![Screenshot 2022-08-18 113414.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1660803859852/P09Ew57as.png)So the reject method moved the promises to the rejected() state.

## Static types and prototype method:

- **Promise.prototype.then(onFulfilled, onRejected)**

`.then` method is used to schedule📅 a callback to be executed when the promise is successfully resolved.

- **Promise.prototype.catch(onRejected)**

`.catch` method is used to schedule📅 a callback to be executed when the promise is rejected.

- **Promise.prototype.finally(onFinally)**

`.finally` is used to execute the same piece of code whether the promise is fulfilled or rejected.

**For example📃** ,

```
function makePromise(wakeUp) {
    return new Promise(function (resolve, reject) {
       setTimeout(() => {
           if (wakeUp) {
               resolve("I woke up at 5AM.");
           } else {
               reject("I didn't wake up at 5Am.");
           }
       }, 5 * 1000);
   });
   }
   let wakeUp = makePromise(true);
   wakeUp
       .then(success => console.log(success))
       .catch(reason => console.log(reason))
       .finally(() => console.log("Let's sleep"));

```

**Output:**

![Screenshot 2022-08-18 131219.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1660808551458/_-LFTKNcG.png)

## Promise🤞 Chaining

Promise Chaining is a concept by which we may initialize another promise inside our .then() method and accordingly we may execute our results.

**For example📃** ,

```
let promise = new Promise((resolve, reject) => {
    resolve("Test");
  });
  promise
    .then(
      new Promise((resolve, reject) => {
        resolve("exams");
      })
      .then((result1) => {
        console.log(result1);
      })
    )
    .then((result2) => {
      console.log(result2);
    });

```

**Output:**

![Screenshot 2022-08-18 161853.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1660819744624/a5FPly52M.png)

We can use `promise.all()` for the nested `.then` method. It can simply the messy code easily. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

**For example📃** ,

```
const Promise1 = new Promise((resolve, reject)=>{
    setTimeout(() => {
        console.log('The first promise has resolved');
        resolve(10);
      }, 1 * 1000);
})
const Promise2 = new Promise((resolve, reject)=>{
    setTimeout(() => {
        console.log('The second promise has resolved');
        resolve(10);
      }, 1 * 1000);})
Promise.all([Promise1, Promise2])
    .then((data)=>{
        console.log(data);
    })
    .catch((error)=>{
        console.log(error)
    })

```

**Output:**![Screenshot 2022-08-18 161853.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1660822852808/HZ1fWRob8.png)

## Important points

- Use promises whenever you are using async or blocking code.
- A promise is an object that returns a value in the future.
- A promise starts in the pending state and ends in either a fulfilled state or a rejected state.
- `resolve` maps to `then` and `reject` maps to `catch`
- If something needs to be done in both cases use `.finally`

Thanks for reading my post. I hope you've liked it. Happy coding😊

Some more blogs by me💗

[Some best techniques to Optimize your React App🐱💻](https://blog.sagarmedtiya.me/some-best-techniques-to-optimize-your-react-app)

[Component Lifecycle🌀 in ReactJS🚀](https://blog.sagarmedtiya.me/component-lifecycle-in-reactjs)

[Know Your JavaScript🤌](https://blog.sagarmedtiya.me/know-your-javascript)