CodeBlanks Logo Icon CodeBlanks

Fetching data with fetch

JavaScript course · Intermediate · Lesson 92/134

Fetch weather data from an API using fetch and async/await.

async function and fetch

When fetching data from a server, fetch returns a Promise. With the await keyword we wait for that promise's result. await can only be used inside a function marked async. We define a function like async function fetchWeather(city). Inside it we send the request with await fetch(url), read the body as text with await response.text(), and return the result. Each await waits for one step.

Two-step waiting

In a fetch request you typically use await twice. The first await waits for the request to finish and gives you a Response object. The second await waits for the body to be read. With const response = await fetch(url) you get the response; with const info = await response.text() you read the body as text. Keeping the two steps separate gives flexibility: you can check the status first, then process the body.

Exercise Define the async fetchWeather function

Continue on top of the previous lesson's solution. Define an async function fetchWeather(city). Inside it, assign the template literal `https://api.example.com/weather?city=${city}` to a url variable. Get the response with const response = await fetch(url), read the body with const info = await response.text(), and return it with return info.

Show example solution
const app = document.querySelector("#app");
const cityInput = document.querySelector("#cityInput");
const getWeatherButton = document.querySelector("#getWeatherButton");
const weatherResult = document.querySelector("#weatherResult");
console.log(app, cityInput, getWeatherButton, weatherResult);

function getWeather() {
  const city = cityInput.value;
  console.log(city);
}

getWeatherButton.addEventListener("click", getWeather);

async function fetchWeather(city) {
  const url = `https://api.example.com/weather?city=${city}`;
  const response = await fetch(url);
  const info = await response.text();
  return info;
}

Test yourself

  1. What does await response.text() give you?

    const info = await response.text();
    • A Response object
    • The body as text
    • A status code
    • A Promise object
    Show answer

    The body as text — Correct! await gives the body as text.

  2. Wait for the fetch request

    const response = ____;
    Show answer
    const response = await fetch(url);
  3. Match the fetch steps

    fetch(url)
    Sends the request
    await
    Waits for the result
    response.text()
    Reads the body
    return
    Returns the value
  4. Match the fetchWeather steps

    async function
    Defines the function
    await fetch
    Waits for the request
    await response.text()
    Waits for the body
    return info
    Gives the result

All lessons in Intermediate