Code
main.js — the async load
Now let's use api.js. In the code column — the updated main.js: lesson 1's placeholder becomes a real async load. We show "Loading…", await the network, then a result or an error.
Three states are already here, if still primitive:
- Loading:
app.textContent = 'Loading…'before theawait. - Success: show how many pictures we got and the newest one's title.
- Error:
try/catchcatches both a network failure and ourthrowon!response.ok.
async function load() {
app.textContent = 'Loading space pictures…';
try {
const pictures = await fetchPictures(14);
app.textContent = `Loaded ${pictures.length} pictures. Newest: ${pictures[0].title}`;
} catch (error) {
app.textContent = `Could not load: ${error.message}`;
}
}
load();
Verify. Serve it (python -m http.server) and open it. You should see:
Briefly: Loading space pictures…
Then: Loaded 14 pictures. Newest: <today's APOD title>
Gotcha (the DEMO_KEY limit). Reload the page quickly a few times. Sooner or later, instead of pictures, you'll see:
Could not load: The API returned 429
429 Too Many Requests— theDEMO_KEYquota (~30/hour) is spent. (NASA sometimes returns a403with "rate limit" text too.) This isn't a bug in your code — it's the shared key's limit. The fix is your own key (in the homework). And in lesson 6 we'll turn this into a clear message with a "Retry" button, instead of a blunt "429".