DEV Community

Makoto Tsuga
Makoto Tsuga

Posted on

How to use Promise chaining in Javascript.

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 
➡How to use Async/Await in Promise.

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").

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

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

Image description

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

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

  console.log("A");

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

Image description

How to use it.

This is basic format for a promise.

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

Enter fullscreen mode Exit fullscreen mode

returned object
Image description

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.

    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
      });
Enter fullscreen mode Exit fullscreen mode

Image description

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.

Using this then method allows you to execute subsequent processes sequentially (synchronously) after the asynchronous operation has completed.
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.

    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
      });
Enter fullscreen mode Exit fullscreen mode

Image description

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.

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

  console.log("A");

  new Promise((resolve) => {
    setTimeout(() => {
      func(); //call the func
      resolve();
    }, 4000);
  }).then(() => {
    console.log("C");//Subsequent processing
  });
Enter fullscreen mode Exit fullscreen mode

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").

Promise chaining is commonly used to execute asynchronous operations synchronously like this.

Top comments (0)