Synchronous fetch with async/await

Say goodbye to unintuitive processing of asynchronous requests.

John Paul Ada
Programmers — Developers
2 min readJul 20, 2017

--

TL;DR

async/await allows us to program using asynchronous requests in a synchronous manner using the modern versions of Javascript.

A hypothetical introduction

As web developers, we make requests to APIs a lot — not only to our own APIs but to others’, too. As we all know, they can be a real pain in the ass.

What if we wanted to make a request to a hypothetical API https://api.com ?

What if I told you, you can make requests like this in Javascript?

const response = fetch('https://api.com/values/1');const json = response.json();console.log(json);

Normally, this would be impossible, and normally you’d do something like this:

fetch('https://api.com/values/1')
.then(response => response.json())
.then(json => console.log(json));

That is less readable than the former example.

Although, if you try the former example, it wouldn’t work. Why, you ask? Well folks, we’re missing the magic words!

await

await allows us to wait for the response of an asynchronous request.

To use await in our hypothetical code, we can do this:

const response = await fetch('https://api.com/values/1');const json = await response.json();console.log(json);

Let’s break this down.

In the first line, we make a GET request to https://api.com/values/1. Instead of continuing to the next line, we wait for the request to finish, hence await. When it finishes, it passes the resolved value to the response variable.

In the second line, we get the JSON version of the response. Again, we use await so we can wait for it to complete (or fail) and then pass the result to the json variable.

Finally, in the last line, we log the value of the json variable to the console.

This saves us from writing less-than-adequately-readable code allows us to write cleaner code.

This is a more intuitive way of working with requests.

To help you understand it more, here’s another way of looking at this:

await allows us to wait for a Promise to resolve to a value.

await will return the value only after the Promise is resolved.

Sorry for being redundant but this is so you’d understand. 😄 😅

async

But wait, there’s more! Not really, but there’s something I haven’t told you yet. You know that code we rewrote with await? It won’t work yet.

WHAT!? Ikr.

To make it work, you need to wrap it inside an async function!

This is how you do it:

const request = async () => {    const response = await fetch('https://api.com/values/1');    const json = await response.json();    console.log(json);}request();

You just add the async keyword before the function declaration and run it! EZ!

But don’t just take it from me! Try it out here! Just hit the Run button:

Promise-based request and async/await-based requests.

Also posted in The Practical Dev.

If you like this post, subscribe! 😆

And hit the heart below! 💙

Thanks! 👍

--

--