TL;DR
See it in action on https://stackblitz.com/edit/typescript-x5fftj
GitHub
repo on https://github.com/laurilubi/typescript-async-promise-errorhandling
Basically async is sugar for Promise but it also simplifies while debugging.
javascript
All the statements below are also true for javascript. Typescript gets compiled into javascript.
Nesting
All the statements below work regardless how deep your function calls (stacktrace) are. Eg function
A calls function B which calls function C.
throw vs reject()
Thanks to language interpreter throw and reject()are converted automatically to
what is needed. But for clarity I use:
throwinasyncfunctionsreject()in methods that return aPromise
return is useful for avoiding the execution of the following lines.
But in case you do not break for any reason, only the first resolve() or reject()
has effect.
try-catch with async
The execution of an async or Promise-function happens in the future, basically when
there is nothing else to do currently. Therefore the exceptions that occur in the async or
Promise-function happen after the execution has passed the try-catch block. To
handle that:
- use
awaitif you are in anasyncblock and are calling anasyncfunction - otherwise use
.then()and.catch()