Error Handling with Promises in JavaScript
Handling errors properly in Promises ensures that issues are caught and handled gracefully without breaking the execution flow.
🔹 Basic Error Handling in Promises
If a Promise
rejects, the .catch()
method captures the error.
✅ Output (after 2 sec):
✔ Once an error occurs, no further .then()
executes.
🔹 Catching Errors Anywhere in the Chain
Errors propagate down the chain until caught by .catch()
.
✅ Output (after 1 sec):
✔ Any error thrown in a .then()
jumps to .catch()
.
🔹 Using .finally()
for Cleanup
The .finally()
method always executes whether the Promise
resolves or rejects.
✅ Output (after 1.5 sec):
✔ Use .finally()
for UI cleanup, logging, etc.
🔹 Handling Errors in async/await
With async/await
, use try...catch to handle errors.
✅ Output (if the URL fails to fetch):
✔ Error handling is clearer with try...catch
.
🔹 Catching Errors from Multiple Promises
Using Promise.all()
, if one fails, the entire Promise.all()
fails.
✅ Output (if one request fails):
✔ If one request fails, Promise.all()
rejects immediately.
🔹 Using Promise.allSettled()
to Handle Errors Separately
Unlike Promise.all()
, Promise.allSettled()
waits for all promises and returns results for both success and failure.
✅ Output (success & failure info):
✔ Safer when handling multiple requests!
🔹 Summary
✔ .catch()
captures errors anywhere in the chain
✔ .finally()
runs always (cleanup)
✔ async/await
uses try...catch
for better readability
✔ Promise.all()
fails if one fails
✔ Promise.allSettled()
handles both success & failure
🚀 Want more details? Let me know! 😊