Using Async / Await

Rewrite a promise chain (then/catch) with async and await, so an API call reads top to bottom and errors land in a try/catch block.

Journeyman · JavaScript · REST API · Updated

By

In JavaScript, API calls are handled using promises. Upon completion, a promise executes either the success or the error function depending on the result of the action in the promise.

The following example uses POST to add a new category. If the insert is successful, the then callback runs. If the response has any status other than 2xx, the catch callback runs.

const baseUrl = 'http://localhost:8080/api/categories';

function addNewCategory(category)
{
    return axios.post(baseUrl, category)
                .then(response => response.data)
                .catch(error => {
                    console.log(error);
                    throw error;
                });
}

The async/await syntax makes working with promises feel more natural. The syntax was added in 2017.

The await keyword instructs the JavaScript runtime that the block of code will await the result of the promise. This way, there is no need to define a then/callback function for the promise to return to.

Any code that will await a promise, must be marked as async. This is basically a flag stating that the function will return a promise.

We can then use a try/catch block to write our code.

const baseUrl = 'http://localhost:8080/api/categories';

async function addNewCategory(category)
{
    try
    {
        const response = await axios.post(baseUrl, category);
        return response.data;
    }
    catch (error)
    {
        console.log(error);
        throw error;
    }
}

Do it: get a category's label with async and await

The categories page shows a short label for the category a shopper picked, such as Seafood: Seaweed and fish. When the API can't find the category, the page shows No such category instead of breaking. Write the function that gets the label, with async and await, as this lesson does.

The practice box can't load Axios from a CDN, so its page holds a small stand-in that works like Axios's get (you can read it in the page's HTML). It has no real API either, so it answers the requests itself, the way your categories API would:

The request The API answers
GET http://localhost:8080/api/categories/2 200, with { "categoryId": 2, "categoryName": "Condiments", "description": "Sauces and spreads" }
GET http://localhost:8080/api/categories/8 200, with { "categoryId": 8, "categoryName": "Seafood", "description": "Seaweed and fish" }
GET http://localhost:8080/api/categories/300 404: there's no such category, and the Axios promise fails with the message Request failed with status code 404

The function gets one value:

  • id: the category's id, a number, such as 8.

For example, categoryLabel(8) sends GET http://localhost:8080/api/categories/8, waits for the answer, and its promise gives back exactly:

Seafood: Seaweed and fish

Your job: write categoryLabel(id) as an async function, with await and a try/catch block instead of .then.

  • await Axios's get for baseUrl, a slash, then the id: http://localhost:8080/api/categories/8.
  • Return <categoryName>: <description> from the response's data, such as Seafood: Seaweed and fish.
  • When the request fails, print the error's message with console.log (such as Request failed with status code 404), and return No such category.

Practiced live on the lesson page: write the JavaScript right there and check it.

Cheat sheets