Skip to content
Advertisement

Why would you try-catch around a promise? Does that catch the promise’s error?

I stumbled upon some code that looked off to me:

JavaScript

If some somePromise() fails, would this not get caught, and the app would crash? Does this try-catch even do anything?

Should be this, correct?:

JavaScript

Advertisement

Answer

TL;DR – If a function that returns a promise throws an exception before returning the promise then that exception would have to be caught in a regular try-catch block.

Consider this function

JavaScript

This would print “Try caught good old exception”

JavaScript

This would print “Promise caught fancy exception”

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement