DEV Community

loading...
Cover image for JavaScript Interview Question #19: Catching the rejected Promise

JavaScript Interview Question #19: Catching the rejected Promise

coderslang profile image Coderslang: Become a Software Engineer Originally published at learn.coderslang.com on ・1 min read

js-test-19

Can you catch the Promise rejection in JS? Another unhandled rejection?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

In JS, it’s impossible to catch the unhandled promise rejection using the regular try/catch blocks.

So, if the rejection does take place, then we’ll likely see a message like UnhandledPromiseRejectionWarning … or something along these lines.

Here, though, we don’t get to reject the promise properly.

JavaScript tries to evaluate the result of null.length which happens synchronously. An error Cannot read property 'length' of null will be thrown and caught in the catch block.


ANSWER: the error will be caught and the string the error was caught! Cannot read property 'length' of null will be logged to the screen.

Learn Full Stack JavaScript

Discussion (2)

pic
Editor guide
Collapse
jmitchell38488 profile image
Justin Mitchell

This question is missing a lot of other associated content around promises. Such as having a basic understanding of asynchronous requests, different mechanisms, then handling responses, success & failure.

Just asking if it's caught in a try/catch isn't very practical, it's not questioning anything

Collapse
coderslang profile image
Coderslang: Become a Software Engineer Author

This question is more about attention to detail than anything else.