Start learning free

LESSON 48 OF 161 · FRONTEND: TALKING TO AN API

async and await in JavaScript

Practice

The .then chain from the last lesson works, but its steps sit inside functions passed to other functions. async and await let you write the same steps top to bottom, like ordinary code.

Put async before function, and inside that function you may write await in front of a promise. await pauses the function until the promise is ready, then gives you the value inside:

async function loadCart() {
  const response = await fetch("/api/cart");
  console.log(response.status);
}

loadCart();

await pauses only its own function. The rest of the page goes on: the line after the call runs at once, and the visitor can still click. That's why the check now prints the screen while waiting, then what changes when the answer arrives. A function you write but never call does nothing, and no request leaves.

The check opens the page, then clicks "Add to cart" on the Mug. It must print:

> open the page
  request: GET /api/products ...
  screen while waiting:
    …
        text: 0 products
        list (empty)
  answer: GET /api/products -> 200
  screen changes:
    +     text: 8 products
    +       item: Mug $12
    …
> click "Add to cart" in "Mug"
    +       item: Mug x 1 $12
    +     text: Total: $12

Your task: write an async function loadProducts. It awaits the fetch of /api/products, awaits response.json(), puts the data into products and calls render. Then call it, above the render(); at the end of the file.


Assignment
Follow the Coding Tutorial to load the products with an async function that uses await, and call it when the page starts.


Hint
You need two awaits: one for fetch, which brings the response, and one for response.json(), which brings the array. Without the call loadProducts();, nothing in the function runs.


STEP 1 OF 6
    Ctrl + Enter to check

    Fetch Async Await in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free