Promises Chaining in JavaScript

Promises Chaining in JavaScript
October 12, 2023

What is a Promise?

Firstly, a Promise is a JavaScript object that represents the eventual completion or failure of an asynchronous operation. It can be in one of three states:

1. Pending: Initial state; neither fulfilled nor rejected.

2. Fulfilled: Completed successfully.

3. Rejected: Completed with an error.

Why Chain Promises?

Chaining promises is like creating a sequence of tasks where one task starts after the previous one finishes. Instead of nesting callbacks (which leads to "callback hell"), we can make our code cleaner and more readable by chaining promises.

How to Chain Promises?

Chaining is made possible by the fact that the .then() and .catch() methods of a Promise always return a new Promise.

Example: Making a Sandwich

Imagine you're making a sandwich, and you have three steps:

1. Get bread.

2. Add fillings.

3. Serve the sandwich

Each step must be done in order, and you can't start one until the previous is finished. Let's assume each of these steps is an asynchronous task.

function getBread() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('Got the bread!');
      resolve('Bread');
    }, 1000);
  });
}


function addFillings(bread) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('Added fillings!');
      resolve(bread + ' + Fillings');
    }, 1000);
  });
}


function serve(sandwich) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('Sandwich is ready to eat!');
      resolve(sandwich);
    }, 1000);
  });
}


// Chaining the Promises
getBread()
  .then(addFillings)
  .then(serve)
  .then(finalProduct => console.log(`Enjoy your ${finalProduct}!`))
  .catch(error => console.log(`Something went wrong: ${error}`));


Here's a breakdown:

1. We start by calling getBread().

2. Once that promise is fulfilled, .then(addFillings) is invoked, which waits for the bread and then adds fillings.

3. Afterward, .then(serve) is called, serving the sandwich.

4. Finally, we log the result, which is the sandwich ready to eat!

5. If at any point there's a rejection, .catch() will handle it.

Benefits of Chaining Promises:

  • Readability: Instead of nesting callbacks inside each other, we have a linear flow.
  • Error Handling: With a single .catch() at the end, you can catch any rejection that happens at any point in the chain.

Conclusion:

Chaining promises provides a structured and clean way to handle a sequence of asynchronous operations in JavaScript. It allows us to write more readable code and handle errors more effectively.


Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Are you looking for Front-end Developer Job?

Get Front-end Interview Kit Now, And Be Prepared to Get Your Dream Job

Get Front-end Interview Kit

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates