DEV Community

Cover image for Javascript promise chaining
MR.H
MR.H

Posted on • Updated on

Javascript promise chaining

Javascript promise is a major addition to EcmaScript6 enabling you to work on asynchronous code in a clean and organized manner.

Promise

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

Source: MDN

Javascript promise represents the result of an asynchronous operation, it can be resolved with a .then() or rejected with a .catch() callbacks

Promise Chaining

Javascript chaining is a process of nesting multiple asynchronous operations where the result of one operation is passed as input to another

Here is an example


const firstPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log("Resolving first promise")
        resolve();
    }, 2000)
});

firstPromise
.then(() => {
    console.log("First promise resolved")
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("Resolving Second promise")
            resolve()
        }, 2000)
    })
})
.then(() => {
    console.log("Second promise resolved")
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("Resolving Third promise")
            resolve()
        }, 2000)
    })
}).then(() => {
    console.log("Third promise resolved")
});
Enter fullscreen mode Exit fullscreen mode

output

//After 2 seconds
Resolving first promise
First promise resolved
//After 2 seconds
Resolving Second promise
Second promise resolved
//After 2 seconds
Resolving Third promise
Third promise resolved
Enter fullscreen mode Exit fullscreen mode

In the above example, the firstPromise is resolved and logged after 2 seconds, then the second promise is returned and after 2 seconds it is resolved and it goes on for the third promise

This way, you can chain any number of promises together, creating a pipeline of asynchronous operations.

Error handling

One of the benefits of promise chaining is you can use .catch() method to catch errors that occur at any point in the code.

const firstPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log("Resolving first promise")
        resolve();
    }, 2000)
});

firstPromise
.then(() => {
    console.log("First promise resolved")
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("Rejecting second promise")
            reject("ERROR: Rejecting promise")
        }, 2000)
    })
})
.then(() => {
    console.log("Second promise resolved")
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("Resolving Third promise")
            resolve()
        }, 2000)
    })
}).then(() => {
    console.log("Third promise resolved")
}).catch((error) => {
    console.error("Error in promise chain")
})
Enter fullscreen mode Exit fullscreen mode

Output

//After 2 seconds
Resolving first promise
First promise resolved
//After 2 seconds
Rejecting second promise
Error in promise chain
Enter fullscreen mode Exit fullscreen mode

In the above example, we rejected the promise after resolving the firstPromise hence Error in promise chain is logged and the chain broke

Conclusion

JavaScript Promise Chaining is a powerful technique that allows developers to handle complex asynchronous operations in a simple, readable, and manageable way. By chaining promises together, you can break down complex operations into smaller steps, making your code easier to understand and debug. Additionally, promise chaining allows for code re-usability and helps you write more maintainable code.

Try it yourself

Try to find the output of this below code. Don't execute code immediately, try to find and compare the output by executing

const firstPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve();
    }, 2000)
});

firstPromise
.then(() => {
    console.log("First promise resolved")
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve()
        }, 2000)
    })
}).then(() => {
    console.log("Second promise resolved")
}).catch((error) => {
    console.error(error)
});


firstPromise.then(()=>{
    console.log("First promise resolved in second chain")
})
Enter fullscreen mode Exit fullscreen mode

Please leave a like and share your thoughts in the comments section

HAPPY CODING

Cover photo by Mike Alonzo on Unsplash

Top comments (1)

Collapse
 
matandev profile image
matan2002cse • Edited
const firstPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        ...
        ... 
        ...
        ... 
        ... 
}).catch((error) => {
    console.error(error)
});


firstPromise.then(()=>{
    console.log("First promise resolved in second chain")
})
Enter fullscreen mode Exit fullscreen mode

##This output is:
1st -> First promise resolved
2nd ->First promise resolved in second chain
3rd - >Second promise resolved
Because of after 1st promise it's takes 2 min.so, that the mean time they execute the another resolve of 1st primise.

I think this approch is correct.