javascript · level 2 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The server has no news for today. What shows?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<p id="news">Loading...</p> async function load() {
const news = document.querySelector("#news");
const response = await fetch("https://api.example.com/news/today");
if (!response.ok) { news.textContent = `No news (error ${response.status})`; return; }
const story = await response.json();
news.textContent = story.headline;
}
load();
your turn
Your turn. Load the top scores.
Fill in the word that lets await work inside the function. Then choose what goes between the scores. Press run.
the page your code works on
<h2>Top scores</h2>
<p id="board">Loading...</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- the board lists all three scoresnot checked yet
fix it
It says Loading... forever. Fix it!
the page your code works on
<h2>Pet of the week</h2>
<p id="pet">Loading...</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- the page shows Biscuit the hamsternot checked yet
- There is no error, and nothing is ever fetched. Does any line run the function?
- Defining a function only writes the recipe. Something has to call it.
- Add load(); on a new line at the very end, then press run.
nailed it
your page fetches its own data. :D
- On a page,
awaitworks inside anasync function. - Show a loading message, then replace it with the data.
- Check
response.ok, and show a friendly error when it isfalse.
new words in your collection
- async
- status code
This lesson isn’t saved. A free account remembers every lesson you finish.