javascript · level 2 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
asks a for data, and waits for the reply.
A server is a computer that answers requests over the internet, and fetch(url) sends one. Gwecode answers these lessons with a practice server, so every https://api.example.com/... address in them works here.
Replies take time, so fetch hands back a : a ticket saying the answer is coming. Put await in front and JavaScript waits for the real reply, called a response, before running the next line.
A response's body is JSON text. await response.json() reads it and parses it into objects in one go.
const response = await fetch("https://api.example.com/joke");
const joke = await response.json();
console.log(joke.setup);
console.log(joke.punchline); Forget await and you get the promise itself, not the reply.
guess first
The practice server sends back some pets. What shows?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const response = await fetch("https://api.example.com/pets");
const pets = await response.json();
console.log(pets.length);
console.log(pets.map((pet) => pet.name));
your turn
Your turn. Check the weather.
Gwecode's practice server knows the weather in london, paris and rome. Type one of those cities, then the method that reads the reply's JSON. Press run.
fix it
The football score crashes. Fix it!
score.goalsisundefined, soscoreis not the data yet. What did line 2 hand back?response.json()gives back a promise, asfetchdoes. You have to wait for it too.- Put await before response.json() on line 2, then press run.
nailed it
you fetched data from a server. :D
fetch(url)sends a request and gives back a promise.awaitwaits for a promise to become the real answer.await response.json()turns the reply into objects.
new words in your collection
- server
- fetch
- promise
- await
This lesson isn’t saved. A free account remembers every lesson you finish.