Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 66

Chaining Promises for Sequential Tasks

This lesson is built with resources from youtube.com and dev.to.

Hello! Welcome back to our exploration of asynchronous JavaScript.

In the last lesson, we learned how to consume a single Promise using .then() for success and .catch() for failure. This is a powerful pattern, but what happens when you need to perform multiple asynchronous actions in a specific order? For example, you might need to fetch a user's profile, and only after you have their ID, fetch the articles they've written.

This is a very common scenario. Trying to manage this with nested callbacks leads straight back to the "Pyramid of Doom" we sought to escape. Today, we'll solve this problem by learning how to chain multiple Promises to perform sequential asynchronous tasks. You'll discover how to create clean, readable, and robust workflows for operations that depend on each other.

The Secret to Chaining: .then() Returns a Promise

The entire mechanism of Promise chaining is built on one simple but profound principle we previewed last time: every call to .then() or .catch() returns a new Promise.

This is the key. It allows us to attach another .then() to the result of the first one, creating a "chain."

To see why this is so much better than the alternative, let's look at a classic "callback hell" example from an excellent article by Lydia Hallie.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

The article 'JavaScript Visualized: Promises & Async/Await' opens by perfectly illustrating the problem we're solving today: nested callbacks for sequential operations. This is often called 'callback hell'.

Read just the introductory part of this article, from the beginning down to the 'Promise Syntax' section. Pay attention to the nested structure of the getImage example. This is what we will replace with a clean Promise chain.

That nested code is hard to read and difficult to maintain. Promise chaining flattens this structure, making it linear and logical.


Building Your First Chain

So, how do we use this concept to run asynchronous tasks in sequence?

When you return a value from a .then() handler, one of two things happens:

  1. If you return a regular value (like a number, string, or object), the next Promise in the chain immediately fulfills with that value.
  2. If you return another Promise, the chain pauses. The next .then() will only execute after the returned Promise settles, and it will receive that Promise's fulfillment value.

This second point is what enables sequential asynchronous operations.

The following video provides a fantastic, practical demonstration of building a Promise chain from scratch. The instructor creates a getWeather function and then a getWeatherIcon function that depends on the first one's result.

JavaScript Promises -- Tutorial for Beginners

Watch this segment from 'JavaScript Promises -- Tutorial for Beginners' to see how chaining works in practice. The instructor clearly explains how the result of the first Promise is passed to the next function in the chain.

Watch from 16:06 to 20:30. Observe how getWeather() is called, and then .then(getWeatherIcon) is chained to it. Notice that you don't need to manually pass the 'weather' data; the chain does it for you!

Let's break down the pattern shown in the video with our own example. Imagine we have two functions that return Promises:

  1. fetchUser(userId): Fetches a user object from an API.
  2. fetchUserPosts(userId): Fetches all posts by that user.
// Simulating an API call to get a user
function fetchUser() {
  console.log('Fetching user...');
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({ id: 1, name: 'Learner' });
    }, 1000);
  });
}

// Simulating an API call to get posts for a user
function fetchUserPosts(userId) {
  console.log(`Fetching posts for user ID: ${userId}...`);
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(['Post 1', 'Post 2', 'Post 3']);
    }, 1000);
  });
}

// Now, let's chain them!
fetchUser()
  .then(user => {
    // This handler receives the user object
    console.log(`Success! User is ${user.name}`);
    // We return the *next* promise in the sequence
    return fetchUserPosts(user.id); 
  })
  .then(posts => {
    // This handler receives the result of fetchUserPosts
    console.log(`Success! Found ${posts.length} posts.`);
    console.log(posts);
  })
  .catch(error => {
    // This single .catch handles errors from ANYWHERE in the chain
    console.error('An error occurred:', error);
  });

This code is flat, readable, and clearly expresses the sequence of operations. Each .then() represents a distinct step in the process.

This image beautifully visualizes how a value can be transformed as it passes down a Promise chain.

JavaScript Promise Chaining Flow
This image illustrates how a Promise resolving with `10` is passed through a chain of `.then()` handlers. Each handler performs an operation and returns a new value, which becomes the input for the next step in the chain.

Under the Hood: The Flow of Values

Since you appreciate the deeper mechanics, let's look at how values and Promises flow through the chain. The key is what you return inside your .then() handler.

The following video provides a crystal-clear visual explanation of this process using a simple numerical example.

JavaScript Visualized - Promise Execution

Let's revisit 'JavaScript Visualized - Promise Execution' by Lydia Hallie. This short segment precisely demonstrates how returning a value from one .then() handler passes it to the next one.

Watch from 04:44 to 06:18. Pay close attention to how the result of result * 2 is passed from one then block to the next, and how each .then call itself creates a new Promise object.

As the video shows, when return result * 2 is executed, the new Promise created by that .then() call immediately fulfills with the calculated value. The next .then() in the chain then receives this value.


Error Handling in Chains and .finally()

One of the most elegant features of Promise chains is error handling. You don't need to handle errors at every step. A single .catch() at the end of the chain will handle a rejection from any of the preceding Promises.

If any Promise in the chain rejects, the JavaScript engine will skip all subsequent .then() handlers and jump straight to the nearest .catch().

Additionally, there is a .finally() method. A .finally() handler will always execute when the Promise settles, regardless of whether it was fulfilled or rejected. This is extremely useful for cleanup tasks, like hiding a loading spinner.

JavaScript Promises -- Tutorial for Beginners

Let's return to the 'JavaScript Promises -- Tutorial for Beginners' video, which demonstrates both error handling and the .finally() method in the context of a chain.

First, watch from 23:58 to 28:00 to see how a reject() in one function causes the chain to skip to the .catch() block. Then, watch from 29:39 to 31:54 to understand how .finally() is used for code that must run in either case.


Common Mistakes to Avoid

When learning to chain Promises, two pitfalls are very common. Being aware of them will save you a lot of debugging time.

🧠 JavaScript Promises Explained — A Complete Guide for ...

The article 'JavaScript Promises Explained' has a concise section on 'Common Beginner Mistakes' that is extremely valuable. Let's review it.

Read the section 'Common Beginner Mistakes'. Focus on the two main points: 'Not returning a Promise inside .then()' and 'Nested Promises (Anti-pattern)'.

Let's emphasize the first mistake, as it's the most frequent.

Mistake: Forgetting to return

fetchUser()
  .then(user => {
    console.log(`Got user: ${user.name}`);
    // MISTAKE! We call the next function, but don't return its promise.
    fetchUserPosts(user.id); 
  })
  .then(posts => {
    // This 'posts' variable will be 'undefined'!
    console.log('Received posts:', posts); // logs: Received posts: undefined
  });

Without the return keyword, the second .then() handler runs immediately with undefined as its value, because the first handler didn't explicitly return anything. The fetchUserPosts operation still runs, but it's disconnected from our chain.

Test your understanding!

What will be logged to the console by the following code?

Promise.resolve(10)
  .then(val => {
    console.log(val); // First log
    // Notice there is no 'return' statement here
  })
  .then(val => {
    console.log(val); // Second log
    return 30;
  })
  .then(val => {
    console.log(val); // Third log
  });
Show answer

The console will show:
10
undefined
30

Explanation:

  1. The first .then() receives 10 and logs it. Because it doesn't return anything, it implicitly returns undefined.
  2. The second .then() receives undefined from the previous step and logs it. It then explicitly returns 30.
  3. The third .then() receives 30 from the previous step and logs it.

Conclusion

You have now learned one of the most important patterns in modern asynchronous JavaScript. By chaining Promises, you can write sequential async code that is clean, readable, and easy to debug.

Key Takeaways:

  • Chaining is powered by .then() returning a new Promise. This allows you to create a sequence of dependent steps.
  • To run async operations sequentially, return the next Promise from within your .then() handler.
  • The value passed to the next .then() is whatever was returned by the previous one.
  • A single .catch() at the end of a chain can handle an error from any step.
  • Use .finally() for cleanup code that must run whether the chain succeeds or fails.

Next Up

Promise chains are a massive improvement over callbacks, but in the next lesson, we'll learn about an even more modern and intuitive syntax for working with Promises: async/await. It's "syntactic sugar" built on top of Promises that lets you write asynchronous code that looks almost exactly like synchronous code, making it even easier to read and reason about.