Pages that show the weather, forms that fill in an address for you—all of them bring in data from elsewhere. The door to that is fetch.
Fetching takes time
Commands so far ran the instant you wrote them. A trip across the internet is different: there’s a wait between ordering and receiving.
call fetch → (a few hundred ms to a few seconds) → data arrivesThe word for “wait, then carry on” is await.
The basic shape
async function getData() {
const response = await fetch("https://example.com/api/weather");
const data = await response.json();
console.log(data);
}
getData();Three things to learn:
| What you write | What it means |
|---|---|
async function | Declares “there may be waiting inside this function” |
await fetch(URL) | Wait until a reply arrives from that URL |
await response.json() | Read the reply’s contents as JSON (also a wait) |
Two awaits is the first thing that trips people. The first waits for arrival, the second for the contents to finish being read. Arriving and being read are separate things.
Putting the data on the page
What you get back is an ordinary object, so everything you already know applies.
async function showWeather() {
const response = await fetch("https://example.com/api/weather");
const data = await response.json();
document.querySelector("#city").textContent = data.city;
document.querySelector("#temp").textContent = data.weather.temp + "°C";
}
showWeather();JavaScriptJSON: the shape data travels inThe shape of what comes back (JSON), in this lessonBeing ready for failure
Networks fail regardless of your plans. Not writing for the happy path only is the professional habit.
async function showWeather() {
try {
const response = await fetch("https://example.com/api/weather");
if (!response.ok) {
throw new Error("The server returned an error: " + response.status);
}
const data = await response.json();
document.querySelector("#city").textContent = data.city;
} catch (error) {
console.log(error);
document.querySelector("#city").textContent = "Could not load";
}
}try…catch—on failure, control moves tocatchresponse.ok—catches the connection succeeding but a 404 coming back- Show “Could not load”—never leave the visitor staring at a blank space
You’ll also see .then()
Older articles and other people’s code often use this shape.
fetch("https://example.com/api/weather")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));It does the same thing as async/await. await reads better, so write that for new code. Recognizing this one when you see it is enough.
CORS—you can’t just take another site’s data
Fetching from a different domain can produce this:
Access to fetch at '...' from origin '...' has been blocked by CORS policyIt means the source hasn’t allowed other sites to read it. You can’t fix that from your side.
- Use APIs published for public use (they’re configured to allow it)
- Open your page through a development server (like Live Server) rather than as a
file://document
Don’t put API keys in your HTML
Summary of this lesson
fetchbrings in outside data. There’s a wait, so youawaititawait fetch(URL)waits for the reply;await response.json()reads it—two awaits- Guard with
try/catchandresponse.ok. Never put an API key in the page