×

javascript · level 2 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An function can fetch data and draw it on the page.

On a page, await only works inside a function marked async, like async function load() { }. Call load() and it starts, pauses at each await while the page stays usable, and carries on when the reply arrives.

Show a loading message first, so people know something is happening. Then fetch, and swap the message for the data.

Every reply carries a : 200 means OK and 404 means not found. response.ok is true for good replies, so a guard clause can show a friendly error. The practice server answers here too.

<h2>Today's specials</h2>
<p id="specials">Loading...</p>
async function load() {
  const specials = document.querySelector("#specials");
  const response = await fetch("https://api.example.com/specials");
  if (!response.ok) { specials.textContent = "Sorry, the menu is missing."; return; }
  const dishes = await response.json();
  specials.textContent = `Today: ${dishes.join(", ")}`;
}
load();

Press run it to bring the page to life.

console

nothing logged yet

On its own line at the top of a page script, await is a SyntaxError. Keep it inside an async function.