How to use Promise chaining in Javascript.
Tags: webdev, javascript, beginners
Published: 2024-05-23 20:58:04

Hello, everyone. In this article, I would explain promise chaining in javascript. It is recommended to read the following article and understand the concept of asynchronous and synchronous processing before reading this article. This is because these concepts is connected with Promise. Moreover, please read the following article for information on how to use Async/Await, a different implementation of PROMISE. 
[➡async/sync in Javascript　](https://dev.to/makoto0825/asyncsync-in-javascript-438e)
[➡How to use Async/Await in Promise.](https://dev.to/makoto0825/how-to-use-asyncawait-in-promise-38hc)

## What is promise?
Promise is an object that represents the completion or failure of synchronous processing. By using this object, you can wait for asynchronous processing to complete and then execute the next process sequentially.

In the following case, it is not possible to output in the order of ABC. Instead, it outputs in the order of ACB. This is because the asynchronous function setTimeout delays the execution by 4000ms, causing console.log("C") to be executed before console.log("B").

```javascript
  <script>
    //=== function declaration ==========
    const func = () => {
      console.log("B");
    };

    //  === program start ==========
    console.log("A");
    setTimeout(func, 4000); //async function
    console.log("C");
  </script>
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ncl6eiz2edklz2ep3vn3.png)


However, if you use Promise chaining , you can output in the order of ABC.

```javascript
<script>
  const func = () => {
    console.log("B");
  };

  console.log("A");

  new Promise((resolve) => {
    setTimeout(() => {
      func();//call the func
      resolve(); 
    }, 4000);
  }).then(() => {
    console.log("C");
  });
</script>
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nlp41owji6h6pm0vlkye.gif)


## How to use it.
 This is basic format for a promise.

```javascript
    const num = 10;
    const pro = new Promise((resolve, reject) => {
      if (num > 0) {
        resolve("success!!!!!");
      } else {
        reject("failure");
      }
    });
    console.log(pro); //output success

```
**returned object**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vjie9l45dtgtukiqz6w2.png)


Promise can take the functions resolve and reject as arguments. And return promise object.

- resolve: Function called when the operation succeeds
- reject: Function called when the process fails.

In this case, num is greater than 0 so it returns Promise object in successful state thanks to resolve.

## chaining:"resolve" and "then"
When the Promise object is in a successful state due to resolve, subsequent processing can be executed using the following .then() method.
we can call this idea as **promise chaining**.

```javascript
    const num = 10;
    const pro = new Promise((resolve, reject) => {
      if (num > 0) {
        resolve("success!!!!!");
      } else {
        reject("failure");
      }
    });
    pro
      .then((message) => {
        console.log(message);//Subsequent processing1
      })
      .then(() => {
        console.log("process2");//Subsequent processing2
      })
      .then(() => {
        console.log("process3");//Subsequent processing3
      });
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1hbwyuftn160yqyye3tk.png)


By specifying an argument in the then method, the value passed when the resolve method is called is provided. In this case, since "success!!!!!" is passed to resolve, by passing an argument to then, you can output "success!!!!!" with console.log.

**<u>Using this then method allows you to execute subsequent processes sequentially (synchronously) after the asynchronous operation has completed.</u>**
This can be accomplished by placing asynchronous processing before resolve() and subsequent processing within then()

## "reject" and "catch"
When the Promise object in a failed state due to reject, you can handle the error using the .catch() method.

```javascript
    const num = -1;
    const pro = new Promise((resolve, reject) => {
      if (num > 0) {
        resolve("success!!!!!");
      } else {
        reject("failure");
      }
    });
    pro.then((message) => {
        console.log(message);
      })
      .then(() => {
        console.log("process2");
      })
      .then(() => {
        console.log("process3");
      })
      .catch((message) => {
        console.log(message); //error handle
      });
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpgsgjnuxa8r5joeueo7.png)

In this case, num is lesser than 0 so promise object is in failure. Hence, the code is executed inside of catch. 

## Asynchronous Function and Promise chaining
As I mentioned that if you use promise chaining, Asynchronous processing can be executed synchronously.
This is the code introduced at the beginning of the article. 

```javascript
  const func = () => {
    console.log("B");
  };

  console.log("A");

  new Promise((resolve) => {
    setTimeout(() => {
      func(); //call the func
      resolve();
    }, 4000);
  }).then(() => {
    console.log("C");//Subsequent processing
  });
```
Although setTimeout is an asynchronous function and  func should be executed last, using the then method of the promise allows the processing to be completed before console.log("C").

<u>Promise chaining is commonly used to execute asynchronous operations synchronously like this.</u>