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.
const ten = new Promise((resolve, reject) => {
resolve(10);
});
Now, to form a Promise Chain, let us chain a bunch of .then() handler functions:
// 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:
// 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 every time before the .then() handler function. It is not a chain because, we are handling the promise freshly every time with
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.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more