Promise Chaining in Javascript

In the previous blog, we learned about the basics of promises in javascript. Here is the link if you've missed it: https://pulkitgovrani.hashnode.dev/what-are-promises-in-javascript

Now in this blog, we will be learning how promises can handle more than one task using promise chaining.

Promise chaining means performing a particular chain of operations after the promise object is holding the status of an operation.

Syntax of Promise Chaining in Javascript

first_operation().then(
second_operation).then(
third_operation).....

Here is a code example of promise chaining in javascript.

Code:

let promiseobj = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(1);
    }, 500);
});

promiseobj.then((ans) => {
    console.log(ans);
    return ans + 1;
}).then((ans) => {
    console.log(ans);
    return ans +1;
});

Output:

1
2

This output will be visible on the screen after 0.5 seconds.

In the above code, the value returned by the first then method (i.e. ans=2) will be passed onto the second then method. Therefore like this multiple then methods can be attached to each other if their outputs are dependent.

Note: If you are using multiple then methods separately then it will not be considered as promise chaining. Here is a code example.

Code:

let promiseobj = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(1);
    }, 500);
});

promiseobj.then((ans) => {
    console.log(ans);
    return ans + 1;
})

promiseobj.then((ans) => {
    console.log(ans);
    return ans +2;
});

promiseobj.then((ans) => {
    console.log(ans);
    return ans +3;
});

Output:

1
1
1

So this is how promise chaining works in javascript. Feel free to ask your doubts below or type your thoughts in the comment box.