Skip to content
Advertisement

What’s the correct way to handle promise rejections so that the function exits?

Let’s say that I have this code:

JavaScript

If foo returns a rejected promise, then I’d like to exit doSomething(), but the code above does not do this. Instead since the error is caught, the code continues.

If I do not catch the rejected promise then I get an error: UnhandledPromiseRejectionWarning:

JavaScript

I know that I can do this, but this just feels messy:

JavaScript

So what is the best way to handle something like this? It’d be nice to be able to do this:

JavaScript

Or even this:

JavaScript

Does anyone else feel my pain, if so what are is the best (cleanest) way to handle this?

Advertisement

Answer

I suggest using try/catch if you handle promises in async function

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