DEV Community

Cover image for JavaScript Interview Question #27: Handling errors in JavaScript Promise chains
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com on

JavaScript Interview Question #27: Handling errors in JavaScript Promise chains

js-test-27

Are there any differences between f1 and f2?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

If you're not sure what is a Promise in JS or how to use it, read these articles first:

There are two ways of providing error handlers to the JavaScript Promises.

The first one is shown in the function f1. We pass the errorHandler as a second argument to .then().

The second approach is implemented in f2. Here, we add the errorHandler using the .catch() function.

In both cases errorHandler will be called if the original promise is rejected.

If promise resolves successfully, then the execution continues in successHandler. And if successHandler throws the error, then it will only be handled by f2 and not f1.

This happens because of the internal implementation of .catch(). It handles all errors in the promise chain, including the ones inside of the .then() handlers.


ANSWER: Yes, there’s a big difference between f1 and f2. The former doesn’t handle the error in successHandler (if it appears) and the latter does.

Learn Full Stack JavaScript

Top comments (3)

Collapse
 
yodalightsabr profile image
YodaLightsabr

I had no clue that there was a way to only catch the first promise! This is amazing.

Collapse
 
hossamahmad profile image
Hossam Ahmad

So insightful .. thank you

Collapse
 
coderslang profile image
Coderslang: Become a Software Engineer

🙏