JavaScript Promise Chain vs No-Chain
JavaScript
Async Programming
Frontend

JavaScript Promise Chain vs No-Chain

Learn how to use promise chain in JavaScript for a better data management.
atapasatapas2 min read

Promise Chain vs. No-Chain

A promise chain is formed when we append multiple promise handler functions(like, .then() or .catch()) to handle results and errors. However, at times you could be mistaken that you need to prefix the promise everytime you want to form a chain.

Let's understand it with the following examples:

First, here is a simple promise created with the Promise() constructor function. The promise resolves immidiately with a result value of 10.

JS
const ten = new Promise((resolve, reject) => {
    resolve(10);
});

Now, to form a Promise Chain, let us chain a bunch of .then() handler functions:

JS
// Promise Chain

ten.then((result) => {
    // returns 20
    return result + 10;
})
.then((result) => {
    // returns 200
    return result * 10;
})
.then((result) => {
    // returns 190
    return result - 10;
})
.then((result) => {
    // logs 190 in console
    console.log(result);
});

It has formed a perfect Promise Chain to pass the result from one handler function to another, and finaly print the end result into the console. The final result output is a number, i.e, 190.

Now, let us change the above code to the following:

JS
// No Chain

ten.then((result) => {
    // returns 20
    return result + 10;
});
ten.then((result) => {
    // returns 100
    return result * 10;
});
ten.then((result) => {
    // returns 0
    return result - 10;
});
ten.then((result) => {
    // logs 10 in the console.
    console.log(result);
});

As you notice, we have now prefixed the promise ten everytime before the .then() handler function. It is not a chain because, we are handling the promise freshly everytime with

JS
ten.then((result) => {
    // DO SOMETHING...
});

We are not passing the resolved result of the previous promise to the next one. Hence the output will be, 10. It is a common mistake developers make with JavaScript Promises.

Want to learn further?

Learn about other common mistakes developers make in handling JavaScript Promises.

Day 26: 6 Common Mistakes with JavaScript Promises & Async Code 🤩 - In this session, we’ll break down 6 common mistakes developers make while working with Promises and async code — and most importantly, how to avoid them! Whether you’re just learning or brushing up, this video will help you write cleaner, bug-free asynchronous code.

Learn Full Stack

with tapaScript

By clicking Sign Up you re confirming that you agree with our Terms and Conditions.

newsletter

Don't forget to connect with us on