JavaScript Promise Chaining

JavaScript Promise Chaining

JavaScript Promise Chaining

Promise chaining allows multiple asynchronous operations to be executed sequentially, ensuring each completes before the next starts. It prevents callback hell and improves code readability.

🔹 Basic Example of Promise Chaining

Each .then() receives the result of the previous .then().

new Promise((resolve) => { setTimeout(() => resolve(1), 1000); // Initial value after 1 sec }) .then((result) => { console.log("Step 1:", result); return result * 2; }) .then((result) => { console.log("Step 2:", result); return result * 2; }) .then((result) => { console.log("Step 3:", result); return result * 2; }) .then((result) => { console.log("Final Result:", result); });

Output (with delays)

Step 1: 1 Step 2: 2 Step 3: 4 Final Result: 8

✔ Each .then() gets the previous result and modifies it.

🔹 Using Promise Chain with Async Tasks

We can use fetch() to chain multiple API calls in sequence.

fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) // Convert response to JSON .then((post) => { console.log("Post Title:", post.title); return fetch(`https://jsonplaceholder.typicode.com/users/${post.userId}`); }) .then((response) => response.json()) .then((user) => { console.log("Author:", user.name); }) .catch((error) => console.error("❌ Error:", error));

Output (depends on API response)

Post Title: Lorem Ipsum... Author: John Doe

Each .then() processes and returns a new Promise.

🔹 Handling Errors in Promise Chaining

If an error occurs anywhere in the chain, it goes directly to .catch().

new Promise((resolve, reject) => { setTimeout(() => reject("Something went wrong!"), 2000); }) .then((result) => { console.log("This will never run"); return result * 2; }) .catch((error) => { console.log("❌ Caught Error:", error); });

Output (after 2 sec)

Caught Error: Something went wrong!

No further .then() runs after an error.

🔹 Returning a New Promise in Chain

Each .then() can return another Promise, enabling sequential async execution.

function delayedResult(value, delay) { return new Promise((resolve) => { setTimeout(() => resolve(value * 2), delay); }); } delayedResult(2, 1000) .then((result) => { console.log("Step 1:", result); return delayedResult(result, 1000); }) .then((result) => { console.log("Step 2:", result); return delayedResult(result, 1000); }) .then((result) => { console.log("Final Result:", result); });

Output (each step waits 1 sec)

Step 1: 4 Step 2: 8 Final Result: 16

Each step runs sequentially after the previous one completes.

🔹 Using Promise.all() in a Chain

Promise.all() executes multiple Promises in parallel and continues when all resolve.

function fetchData(id) { return new Promise((resolve) => { setTimeout(() => resolve(`Data ${id}`), 1000); }); } Promise.all([fetchData(1), fetchData(2), fetchData(3)]) .then((results) => { console.log("✅ All Results:", results); });

Output (after 1 sec)

All Results: [ 'Data 1', 'Data 2', 'Data 3' ]

Faster execution when parallel tasks are possible!

🔹 Converting to async/await (Cleaner Code)

Instead of chaining .then(), use async/await for better readability.

async function processSteps() { let result = await delayedResult(2, 1000); console.log("Step 1:", result); result = await delayedResult(result, 1000); console.log("Step 2:", result); result = await delayedResult(result, 1000); console.log("Final Result:", result); } processSteps();

Same output, but cleaner structure!

🔹 Summary

Each .then() receives the previous .then()'s result
Errors are caught with .catch()
Returning a Promise allows sequential execution
Use Promise.all() for parallel execution
Convert to async/await for cleaner syntax

🚀 Want more details? Let me know! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close