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()
.
✅ Output (with delays)
✔ 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.
✅ Output (depends on API response)
✔ 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()
.
✅ Output (after 2 sec)
✔ No further .then()
runs after an error.
🔹 Returning a New Promise in Chain
Each .then()
can return another Promise, enabling sequential async execution.
✅ Output (each step waits 1 sec)
✔ 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.
✅ Output (after 1 sec)
✔ Faster execution when parallel tasks are possible!
🔹 Converting to async/await
(Cleaner Code)
Instead of chaining .then()
, use async/await
for better readability.
✅ 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! 😊