Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
As you should already know, a promise can be rejected. So you should ask yourself: How do we deal with a rejected promise when using async
and await
?
If you remember the playground on promises, you learned this:
You can use the promise's
catch
like a normalcatch
. And everything is simple to understand. Keep in mind that athen
callback can crash. It can throw an error (with an explicit throw or by trying to access a property of anull
variable). Thecatch
method will also catch these crashes. Repeat to yourself: the promise'scatch
method is like a normalcatch
.
So, what is the most natural way to handle an error when using async
and await
? Yes, you have it. Use a simple try { ... } catch (error) { ... }
. Look at the following example:
If you want to return a rejected promise in an async
function, you just have to throw an error. Look at this example: