Fetch and async/await

JavaScript in the browser runs on a single thread. If you stop the thread to wait for a network response, the entire page freezes. fetch returns a Promise so the browser can keep working until the data arrives. async and await are the nicer way to write code that waits for promises.

script.js
javascript
async function fetchBooks() {
  try {
    const response = await fetch('./books.json');

    if (!response.ok) {
      throw new Error('HTTP ' + response.status);
    }

    const books = await response.json();
    renderBooks(books);
  } catch (err) {
    console.error('Failed to fetch books:', err);
    showError('Could not load the catalog.');
  } finally {
    loading.style.display = 'none';
  }
}

Fetch books, check for a failed response, parse JSON, hand off to the renderer.

Read it carefully. The awaits are for two different promises: the network response and the JSON body parsing. The try/catch covers both of them in one place. The finally block runs no matter what, which is exactly where the loading indicator should be hidden. Same shape you will reuse everywhere async code meets the DOM.

Quiz: Quiz

Loading practice…