In this post I will show how to simplify promise handling using async and await in TypeScript.

Asynchronous execution is one of the most important features of JavaScript. It's also one of the features many developers seem to struggle with.

In my experience improper handling of asynchronous code is the main source of bugs in JavaScript applications.

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.

getPersonFullNameUsingThen() { return fetch('./data/person.json') .then((response: any) => { return response.json(); }) .then((person: any) => { console.log(`${person.firstName} ${person.lastName}`); }) }

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.

async getPersonFullNameUsingAsync() { let response = await fetch('./data/person.json'); let person = await response.json(); console.log(`${person.firstName} ${person.lastName}`); }

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.