Asynchronous functions: async/await

Alexis Rangel
Nov 7 · 3 min read

If you’ve ever spent any time in front-end development, you’ve probably had your fair share of headaches waiting around for a server to get back to you. These things just take time, and there’s no way around it. So, how do we get around it?

What is an asynchronous function?

Via the Mozilla web documentation, an “asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result.” Ok, not very helpful.

‘Asynchronous’ just means that things don’t always happen in the order that you would expect. Normally, you just create some data, and then you instantly have access to it, seeing as how you just made it. What happens when you don’t want to make your own data, but instead use something far more interesting that someone else has already made for you. In that case, you might think that you could just send off a quick request for that data and then boom, problem solved. It’s a little bit more complex than that. When you send off a HTTP GET request, often times it’ll take the server more time than your regular synchronous programming language is expecting. You have to explicitly let your program know that this is something it should a(wait) to finish, and then carry on executing the rest of the code. We could do this a couple of different ways. In this example, we’ll be using JavaScript and the fetch() function to send a request to http://api.open-notify.org/astros.json, which will tell us how many people are currently in outer space. Cool, right?. We’ll also be using .then() to handle and resolve the Promise in the response we get back. (More on Promises here.)

const data = fetch(‘http://api.open-notify.org/astros.json');console.log(data); // => Promise {<pendin>}

This will return a Promise, with a status of pending. Not very exciting. Because asynchronous functions return a Promise, we have handle the response in some way, and then resolve the Promise.

fetch(‘http://api.open-notify.org/astros.json').then( response => response.json()).then( json => console.log(json)); // => proper JSON data

So what’s happening here? First, we’re sending off a request and then receiving a Promise in response. Then after it’s done, we’re taking that response and using the Body.json() function to read the body of the response and parse it as json, a format that we can use. But this operation could still take some time, so instead of just returning the json, it returns another Promise. We use .then() again to handle that, and at the end we grab whatever’s left and print it out. When we print this out, it should look a little something like this. It’s important to note that the argument for .then() is a callback function, a block of code to be executed when the previous operation is done. Here we’re using some fancy ES6 syntax, but you could also write it like this:

fetch(‘http://api.open-notify.org/astros.json').then( function(response) {  return response.json();}).then( function(json) {  console.log(json); // => same JSON stuff})

A bit more typing, but it works the same. Either way, it’s still kind of hard to look at, what with all that being pretty much one line of code.

Async/Await

Instead of writing .then() over and over again, you could define your function using the async keyword, to let JavaScript know that you want this function to happen asynchronously. So all that mess from before, becomes this:

async function getAstronauts(url=’http://api.open-notify.org/astros.json') {  const response = await fetch(url);  const json = await response.json();  console.log(json);}getAstronauts(); // => cool JSON stuff

Much cleaner, in my opinion. Being that it’s a function, a block of code meant to be reused, it’ll work with pretty much any URL you like.

When you work as front-end developer, asynchronous operations are just something you have to deal with and understand. But if you dig a little deeper and use some ES6 magic, becoming a successful programmer is actually pretty doable.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade