Advance JavaScript (DOM, BOM, Web API) / Asynchronous JavaScript

Promise Chaining

Promise chaining means calling multiple .then() methods one after another, where

each step uses the result of the previous step.

It helps run asynchronous tasks in order, avoiding callback hell.


🧠 Why use Promise Chaining?

  • To perform tasks step-by-step

  • To avoid nested callbacks

  • To handle async code cleanly

  • To pass and transform data between steps


🍔 Real-Life Example: Ordering a Burger

Imagine you order a burger at a restaurant.

Steps happen one after another:

  1. Place order

  2. Chef prepares the patty

  3. Burger is assembled

  4. Order is packed

  5. You receive the burger

Same step-by-step process happens in promise chaining.


✔ Each step depends on the previous one

✔ Perfect representation of Promise Chaining


🧩 How Promise Chaining Works

  • Each .then() returns a new promise

  • The returned value is passed to the next .then()

  • If a .then() returns a promise, the next waits for it

  • If any step fails → jumps to .catch()


❗ Error Handling in a Chain

doTask1()
  .then(doTask2)
  .then(doTask3)
  .catch((err) => console.log("Error:", err));

🔁 Returning a Promise Inside .then()

fetchUser()
  .then(user => fetchPosts(user.id))
  .then(posts => console.log(posts));

🌟 finally() in Promise Chains

task()
  .then(res => console.log(res))
  .catch(err => console.log(err))
  .finally(() => console.log("Done!"));

🎯 Quick Summary

  • Promise chaining = running async steps in sequence

  • Every .then() creates a new promise

  • Returned values flow to the next step

  • Errors go directly to .catch()

  • .finally() runs no matter what