JavaScript

How to Chain Promises in JavaScript

JavaScript Promise object is used to handle asynchronous functions. It represents the state and data returned by the specified function. The state of the Promise Object can help you determine if the added asynchronous function is completed, rejected, or is still pending.

In JavaScript, Promises are chained together for managing the execution flow in a program. Chaining Promises is also useful when you have to execute a series of asynchronous functions, where each depends on the prior function. It also includes Error Propagation.

This write-up will discuss the procedure to Chain Promises in JavaScript with the help of suitable examples. So, let’s start!

How to create a Promise in JavaScript

You can use the “Promise()” constructor for creating a promise object in your program:

let promise = new Promise(function(resolve, reject){
    //body of the function
})

In JavaScript, the “Promise()” constructor accepts a “function()” as an argument which further have two arguments: “resolve()” and “reject()“. The resolve() function will be invoked if the promise is returned successfully; otherwise, the reject() function will be called.

Example: How to create a Promise in JavaScript
In the below-given program, we will create a Promise object named “numberValue” by utilizing the Promise() constructor. According to the given syntax, we have added the parameters “resolve()” and “reject()” for our promise object:

const number = true;
let numberValue = new Promise(function (resolve, reject) {
    if (number) {
        resolve("We have a number");
    } else {
        reject("We do not have any number");
    }
});

The value of the “number” is set to “true” so in this case the promise will be resolved:

console.log(numberValue);

Execution of the provided program will return the promise object with its state:

How to chain Promises in JavaScript

If you are stuck in a situation where you need to execute multiple asynchronous tasks in a sequence, then Promise Chaining can assist you in this regard.

With Promise Chaining, you can specify the operations after the particular promise is resolved. For this purpose, the JavaScript “then()”, “catch()”, and “finally()” methods are used.

How to chain Promises in JavaScript using then() method

The JavaScript “then()” method is used for appending the handler function to the created promise object. This method comprises “onFulfilled” and “onRejected” parameters, allowing you to handle the scenarios where promises are fulfilled or failed.

Syntax of JavaScript then() method

promiseObject.then(onFulfilled, onRejected);

Here “onFulfilled” and “onRejected” are the argument of the “then()” method. This method will return a Promise object with the result of the handler function.

Example: How to chain Promises in JavaScript using then() method
First of all, we will create a Promise object named “numberValue” with the help of the Promise() constructor:

let numberValue = new Promise(function (resolve, reject) {
  const product = 2;
  resolve(product);
});

After that, we will utilize “then()” method for chaining the functions “successValue()” and “successValue1()”, and “successValue2()” with the “product” as “onFulfilled” argument to the promise:

numberValue
  .then(function successValue(product) {
    console.log(product);
    return product * 2;
  })

  .then(function successValue1(product) {
    console.log(product);
    return product * 4;
  })

.then(function successValue2(product) {
    console.log(product);
    return product * 6;
  });

The added chain of the then() methods will be executed when the specified promise is fulfilled:

How to chain Promises in JavaScript using catch() method

The JavaScript “catch()” method handles the rejected promises or the case when an error occurs. It is considered a good practice to reject a promise rather than generate an error explicitly.

Example: How to chain Promises in JavaScript using catch() method
Now, we will try to add a catch() method in the previous example:

let numberValue = new Promise(function (resolve, reject) {
  reject('Unfortunately, Promise is rejected');
});

numberValue.then(
    function successValue(result) {
        console.log(result);
    },
)

The below-given “catch()” method will be executed if any error occurs:

.catch(
    function errorValue(result) {
        console.log(result);
    }
);

As you can see from the output that the “numberValue” promise is rejected, and “catch()” method is then utilized for handling the error:

How to use finally() method with Promises

The “finally()” method is used in a situation where you have to execute some code regardless of whether the added promise is fulfilled or not.

Example: How to use finally() method with Promises
We have added the JavaScript “finally()” in the following example which will run either Promise is rejected or fulfilled:

let numberValue = new Promise(function (resolve, reject) {
    resolve('Promise is resolved');
});
numberValue.finally(
    function msg() {
        console.log('Code is executed successfully');
    }
);

The above-given output signifies that the code added in the “finally()” method is executed successfully, and the promise is resolved.

Conclusion

Using then() and catch() methods, you can chain Promises in JavaScript. The then() method is utilized to specify the operation that needs to be done when the added promise is fulfilled, whereas the catch() method handles the case when the promise is rejected. This write-up discussed the procedure to chain promises in JavaScript using the then() and catch() methods.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.