Using Async/Await In JavaScript

Introduction

In this article, you will learn how to perform asynchronous programming in JavaScript using async and await keywords. These keywords are used to work with promises with ease and are very easy to use. The keyword ‘async’ before a function makes the function return a promise.

Async/Await

Consider below code

const url = 'https://jsonplaceholder.typicode.com/todos/1'
      fetch(url)
           .then(response => response.json())
           .then(json => console.log(json))
           .catch(err => console.error(error));

Source- JSONPlaceholder - Free Fake REST API (typicode.com) 

When you run this code with browser console or from any web application it will return a JSON object. 

Let’s see how to convert this code with async and await. 

fetch(url) 

This statement will return a promise. We need to add .then (response => response.json()) to get a response, it returns a HTTP response, so .json() is used to get a body of the response in JSON format. 
.catch is used to catch the error from the promise. 

This code snippet used two .then statement and one .catch statement which I wouldn’t prefer to write my code. We can easily clean up the code using async and await. 

Create a new async function and put the URL and fetch statement into the function. 

const loadData = async () => {
    const url = 'https://jsonplaceholder.typicode.com/todos/1'
    await fetch(url);
}

.then() will be replaced with await keyword to wait for a response returned by fetch.

Add a variable to get an actual response. 

const loadData = async () => {
    const url = 'https://jsonplaceholder.typicode.com/todos/1'
    const res = await fetch(url);
    console.log(res);
}
loadData();

 

Now we got a response. Let’s get data from the body of the response. 

const loadData = async () => {
    const url = 'https://jsonplaceholder.typicode.com/todos/1'
    const res = await fetch(url);
    const data = res.json();
    console.log(data);
}
loadData();

res.json() returns the promise. We need to use await keyword to get data from the promise. 

const loadData = async () => {
    const url = 'https://jsonplaceholder.typicode.com/todos/1'
    const res = await fetch(url);
    const data = await res.json();
    console.log(data);
}
loadData();

So, this code looks much cleaner than the code with .then ().

Handling error

This async function is not capable of handling the error if something goes wrong. So, let's include try and catch block to handle the error. 

const loadData = async () => {
    try {
        const url = 'https://dddjsonplaceholder.typicode.com/todos/1'
        const res = await fetch(url);
        const data = await res.json();
        console.log(data);
    } catch (err) {
        console.error(err);
    }
}
loadData();

I have given a wrong URL in the code and you can see the respective error recorded in the console.

Add a return statement to the async function and initialize a new variable for the loadData(). 

const loadData = async () => {
    try {
        const url = 'https://jsonplaceholder.typicode.com/todos/1'
        const res = await fetch(url);
        const data = await res.json();
        return data
    } catch (err) {
        console.error(err);
    }
}
const data = loadData();
console.log(data)

 

From the above image, it is obvious the async function always returns the promise. We can use await Keyword in function call to resolve the promise because “await is only valid in async functions and the top-level bodies of modules”. So, let’s resolve it using then,

const data = loadData().then(response => console.log(response));
console.log(data)

Let’s hack something here for top-level Await.

You can use an Immediately-Invoked Function Expression (IIFE) for top-level Await. 

const loadData = async () => {
        try {
            const url = 'https://jsonplaceholder.typicode.com/todos/1'
            const res = await fetch(url);
            const data = await res.json();
            return data
        } catch (err) {
            console.error(err);
        }
    }
    (async () => {
        const data = await loadData();
        console.log(data);
    })();

Happy Coding !!!