Promises Chaining in JavaScript
⛓ What Is Promise Chaining?
Promise chaining is a technique where multiple asynchronous operations are performed one after the other, each starting when the previous one completes. This is achieved by returning a new promise from within a .then() block.
>>“Chaining allows sequential handling of async tasks with clean, readable code.”
🚀 Why Use Chaining?
- To perform async tasks in a specific order.
- To avoid deeply nested .then() blocks (aka callback hell).
- To return values from one async task to the next.
🔁 Basic Example
Simple Chaining
new Promise((resolve) => {
setTimeout(() => resolve(1), 1000);
})
.then((result) => {
console.log(result); // 1
return result * 2;
})
.then((result) => {
console.log(result); // 2
return result * 2;
})
.then((result) => {
console.log(result); // 4
});📬 Returning Promises in the Chain
If a .then() returns another promise, the next .then() will wait for it to resolve.
Returning a Promise
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => resolve("📦 Data fetched"), 1000);
});
}
fetchData()
.then((res) => {
console.log(res);
return new Promise((resolve) => {
setTimeout(() => resolve("📤 Data processed"), 1000);
});
})
.then((res) => {
console.log(res);
});Note
🧠 The chain continues only when the returned promise is fulfilled.
⚠️ Error Handling in Chains
Use .catch() at the end (or in the middle) of the chain to catch errors in any step.
Handling Errors
Promise.resolve()
.then(() => {
throw new Error("Something went wrong");
})
.then(() => {
console.log("This will be skipped");
})
.catch((err) => {
console.error("Caught error:", err.message);
});🧪 Chain with Fetch Example
This example uses fetch to demonstrate chaining network calls.
Fetch API Chaining
fetch("https://jsonplaceholder.typicode.com/users/1")
.then((response) => response.json())
.then((user) => {
console.log("User:", user);
return fetch("https://jsonplaceholder.typicode.com/posts?userId=" + user.id);
})
.then((res) => res.json())
.then((posts) => {
console.log("User's Posts:", posts);
})
.catch((error) => {
console.error("Error fetching data:", error);
});🧼 Tips
- Always return a value or promise from .then().
- Use .catch() once at the end unless you want specific error blocks.
- Avoid nesting; use chaining instead for clean async flows.
🔗 Further Reading
>>“With Promise chaining, async code can read almost like synchronous code.”