Learn how to use Async/Await!
In brief, in this tutorial we will demonstrate how to use the Async/Await JavaScript feature.
Async/Await Overview
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:
1 2 3 4 5 6 7 8 |
const createRequest = () => getData() .then(data => { console.log(data) return "Finish"; }); createRequest(); |
This is what it looks like with Async/Await
:
1 2 3 4 5 6 |
const createRequest = async () => { console.log(await getData()) return "Finish"; } createRequest(); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
let friendsToInvite = ["John", "Ema", "Steven", "Hans", "Kiana"]; async function inviteFriends(array) { let list = document.getElementById("list"); await Promise.all(array.map(async (item) => { await (item); let friend = document.createElement('li'); friend.appendChild(document.createTextNode(item)); list.appendChild(friend); return list; })) } let button = document.createElement('button'); button.textContent = "Invite all in-game friends"; button.onclick = function () { document.getElementById('main').appendChild(inviteFriends(friendsToInvite)); }; document.body.appendChild(button); |
This is how our Multiplayer Friends List works.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
let friends: string[] = ["John", "Ema", "Steven"]; let invitedFriends: string[] = ["Rose", "Nick"]; async function inviteFriends() { let invitations: string[] = await Promise.all(friends.map(async (friend): Promise<string> => { await (friend); invitedFriends.push(friend); return "done"; })) let elem = document.getElementById("button"); elem.parentElement.removeChild(elem); document.getElementsByTagName("body")[0].innerHTML =`You successfully invited ${invitedFriends.join(",")} to your multiplayer party!`; }; let button = document.createElement('button'); button.textContent = "Invite all in-game friends"; button.onclick = function() { inviteFriends(); }; document.body.appendChild(button).setAttribute('id','button'); |
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!