Loading and Errors

On a slow connection, a server can take several seconds to answer. Until then, the page has nothing to show, and the user doesn't know whether anything is coming at all. That's why pages show a message such as Loading… while they wait, like the pizzeria's Baking your pizza… in the previous lesson, and remove it when the data is there.

And sometimes the server doesn't have what the page asks for. It still answers, but instead of the file, it sends an error with a number, called the status. You may know the most famous one from websites: 404 Not Found, the address doesn't exist, for example because the file name is misspelled. For fetch(), that's not a mistake: an answer is an answer. If the script then reads it with response.json(), it gets the text Not Found, which isn't JSON, and ends with SyntaxError: … "Not Found" is not valid JSON.

That's what response.ok is for: it's true when the server sent the file (status 200, OK) and false when it answered with an error. Check it before you read the data:

async function loadAnimals() {
    message.textContent = "Loading…";
    const response = await fetch("animals.json");
    if (!response.ok) {
        message.textContent = "The animals couldn't be loaded.";
        return;
    }
    const animals = await response.json();
    message.textContent = "";
    // Show the animals here...
}

The message Loading… is set before fetch(), so it's on the page the whole time the script waits. When the response isn't OK, the script shows an error message and ends the function with return. Otherwise, it empties the message and shows the data.

And what if there's no connection at all? Then no answer comes, and fetch() itself fails with TypeError: Failed to fetch. That's an error you can catch with try/catch from the previous lesson. In the preview, the exercise's files always answer, so here you'll check response.ok.

Instructions

While the books are loading, show Loading… in message: set it at the start of loadBooks(), before fetch(). When the books are on the page, empty the message.

If the response isn't OK, show The books couldn't be loaded. in message and end the function with return. Try it: misspell the file name in fetch(), for example as "book.json", and click Run. Then fix the name again.

Start programming for free

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

Or sign up with:

Back

5/9

Next