JavaScript・Working with outside data

fetch: bringing in outside data

Weather, news, anything from elsewhere — fetch is the door. The idea of waiting for something slow, the shape of the code, and how to be ready when it fails.

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 arrives

The 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 writeWhat it means
async functionDeclares “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 lesson

Being 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";
  }
}
  • trycatch—on failure, control moves to catch
  • response.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 policy

It 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
TipsGetting started with developer toolsStart here if you’ve never opened the dev tools

Don’t put API keys in your HTML

Summary of this lesson

  1. fetch brings in outside data. There’s a wait, so you await it
  2. await fetch(URL) waits for the reply; await response.json() reads it—two awaits
  3. Guard with try/catch and response.ok. Never put an API key in the page

Try it

The “fetch” you learned today is not used on Shima’s page (everything it shows is written into the HTML). It’s a tool for pages that use outside data—weather, news, address lookup. Keep it in mind and use it when you need it.

FAQ

What is fetch?
A JavaScript command for bringing in data from the internet. You give it the address (an API URL) and it returns that data.
What happens if I forget await?
You get a Promise—a container meaning "not here yet"—instead of the data. Reaching into it gives undefined, so when a value looks wrong, suspect a missing await.
What is a CORS error?
It means the source you're fetching from hasn't allowed other sites to read it. You can't fix it from your side, so use APIs that are published for public use.