A File from the Server

Now let's ask the server for data. The function fetch() asks for a file at the address you give it. The address works as in <script src="script.js">: "recipes.json" means the file recipes.json next to the page.

The answer doesn't come at once, because the request has to travel to the server and back. So fetch() returns a Promise, a value that arrives later, as you know from the previous lesson, and you wait for it with await:

async function loadAnimals() {
    const response = await fetch("animals.json");
    const animals = await response.json();
    console.log(animals[0].name);
}

loadAnimals();
console.log("Asking the server…");
Asking the server…
Rex

Getting the data takes two steps:

  1. await fetch("animals.json") waits for the server's answer, the response. It tells you how the request went, and it carries the content of the file.
  2. await response.json() reads the content and turns it from JSON into arrays and objects, as JSON.parse() does. Reading takes time too, so it needs its own await.

Both awaits have to be in an async function. And look at the order of what's printed: loadAnimals() sends the request, and while it waits for the answer, the rest of the script runs. The data comes only later.

That's why a typical mistake is to use the data outside the function:

let animals = [];

async function loadAnimals() {
    const response = await fetch("animals.json");
    animals = await response.json();
}

loadAnimals();
console.log(animals.length);
0

When console.log() runs, the server hasn't answered yet, so animals is still the empty array. Everything that needs the data belongs in the function, after the awaits, or in a function called from there.

Instructions

Write an async function loadRecipes() that loads recipes.json with fetch(), reads the response with await response.json() and, for each recipe, appends an li with text like Pancakes (20 min) to recipeList. Call the function at the end of the script.

Above the list, show how many recipes there are: Number of recipes: 4 in countText. Work it out from the length of the array, and put the line where the data is already there.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

3/9

Next