Course contentsShow
← Node.js
Lesson 177 of 1,9803. Asynchronous Patterns and Flow ControlFree lesson

Chaining Dynamic Promise Sequences

You will implement custom logic to chain promises dynamically based on values resolved by previous steps.

In this lesson, you will learn how to build promise chains where the next step is determined by the result of the previous one, rather than following a fixed, pre-written sequence.

Why go dynamic?

So far, you’ve likely used then() to chain static steps: "Do A, then do B, then do C." But in real-world Node.js applications, you often don't know what to do next until you see the result of the current operation. Imagine you are building a data processor: if the first step returns an ID of a "User," you need to fetch their profile; if it returns a "System Alert," you need to log it to a different service entirely.

The Logic

Instead of hardcoding the chain, you return a new promise inside your .then() block based on a conditional check. Because then() always returns a new promise, you can extend the chain as far as your logic requires.

Consider this example:

fetchTask()
  .then(result => {
    if (result.type === 'USER_DATA') {
      return fetchProfile(result.id); // Chain a profile fetch
    } else if (result.type === 'SYSTEM_LOG') {
      return archiveLog(result.message); // Chain an archive process
    }
    return null;
  })
  .then(finalOutput => {
    console.log("Sequence complete:", finalOutput);
  });

Breaking it down

  1. The Decision: The first .then() acts as a controller. It inspects the result and chooses a path.
  2. The Hand-off: By return-ing the new promise (fetchProfile or archiveLog), you force the main chain to wait for that specific operation to finish before moving to the final .then().
  3. Flexibility: You are no longer tethered to a linear path. You are essentially building a roadmap as the application runs, allowing your asynchronous code to adapt to the data it receives.

This pattern is the foundation of building robust, reactive asynchronous workflows in Node.js, ensuring your application stays in sync with the data it processes.

Key Takeaway: By returning different promises based on logic inside a .then() block, you transform static sequences into flexible, dynamic chains that respond to real-time data.