In this post I will show how to simplify promise handling using async and await in TypeScript.
Most of the asynchronous bugs I see are related to promises. Probably because promise handling can get complicated if you're not careful.
Below is a typical example of promise handling using the fetch api.
As you can tell there is a lot going on here.
First we call fetch to trigger the http call. Next we have to deal with two layers of chained 'then' calls to unwrap and print the person's full name.
Async - await
Next I will show how you can use async/await as an alternative to 'then' based promise handling.
On of the benefits of async/await is that it makes asynchronous code appear more like synchronous code. It's important to keep in mind that this is just syntactic sugar though. Under the hood the code is still asynchronous
In the following code I have rewritten the original function using async/await.
The first thing to notice is that the code is a lot less verbose. We no longer have to deal with 'then' functions and callbacks.
Instead we use the await keyword to create the illusion of synchronous looking code.
Async/await is available in TypeScript as of version 2.1
I have put the code on Github in case you are interested in checking it out.