Learn how to use Async/Await!

by Dimitar Kostadinov June. 25, 18 0 Comment

In brief, in this tutorial we will demonstrate how to use the Async/Await JavaScript feature.

Async/Await Overview

JavaScript Async/Await tutorial

In case you missed it, ES 2017 introduced Asynchronous functions and brought us full Async/Await support.

For those JavaScript enthusiasts and our inquisitive readers who have never heard of this topic before, we would give you a quick explanation.

Async/Await is the new way to write asynchronous code. Previous solutions for writing asynchronous code were callbacks and promises. Moreover, Async/Await is built on top of promises. It cannot be used with plain callbacks. In this sense Async/Await is like promises, non-blocking.

We should appreciate Async/Await because it makes asynchronous code look and behave a little more like synchronous code. This is where all the Async/Await power lies.

In order to easily understand the differences between promises and Async/Await, we will show you a very simple example.

Let’s assume we have a function called getData that returns a promise and we want to resolve that promise. We would call and log our data. In the end, we would return “Finish” to ensure everything is done correctly.

Using promise will look like this:

This is what it looks like with Async/Await:

How to use Async/Await to get and manipulate data

Getting data with Async/Await is not difficult. See how you can create a “Multiplayer Friends List” and invite all your friends (asynchronous) by clicking the invite button.

This is how our Multiplayer Friends List works.

Async/Await manipulate data

Notes: Additional files are needed!
See the whole example here!

Ensuring type safety with TypeScript

After our last TypeScript tutorial, let’s practice what we learned. Furthermore, we will mix TypeScript and Async/Await to write something similar to our Multiplayer Friends List.

You can test and play with TypeScript and Async/Await following our TypeScript Tutorial.

Note: In Step 4 of the TypeScript Tutorial replace --target es6 with the latest --target es2017.

Recommended reads:

JavaScript ES 2017: Learn Async/Await by Example
Async/Await Essentials for Production
6 Reasons Why JavaScript’s Async/Await Blows Promises Away
TypeScript – Async and Await
ES2017 Async/Await to the rescue!

Social Shares

Related Articles

Leave a Comment