typescript · level 2 · unit 6 · lesson 3
- 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 the reply comes later.
Most useful apps get their data from a server, a computer that answers requests over the internet. In these lessons Gwecode answers with a practice server, so your requests never leave your browser. Its addresses start with https://api.example.com/.
fetch(url) sends the request and gives back a promise of a reply, so await it. Every reply has a : 200 means all fine, and 404 means nothing lives at that address. reply.ok is true for codes from 200 to 299.
await reply.text() reads the reply's body as a string. That is a promise too.
async function main(): Promise<void> {
const reply = await fetch("https://api.example.com/joke");
console.log(reply.status, reply.ok);
const joke = await reply.text();
console.log(joke);
const missing = await fetch("https://api.example.com/nothing");
console.log(missing.status, missing.ok);
}
main(); Every request takes a moment, which is why fetch gives you a promise.
guess first
Ask for a pet that is not there. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
async function main(): Promise<void> {
const reply = await fetch("https://api.example.com/pets/99");
if (reply.ok) {
console.log(await reply.text());
} else {
console.log(`Sorry, error ${reply.status}`);
}
}
main();
your turn
Your turn. Ask the practice server for the weather.
Fill in the address https://api.example.com/weather/leeds, then the method that reads the reply's body as text.
fix it
The reply is still a promise. Fix it!
- Read the error:
TS2339: Property 'status' does not exist on type 'Promise<FetchReply>'. fetchhands back a promise of a reply, not the reply itself. You need to wait for it.- Put
awaitin front offetchon line 2, then press run.
nailed it
you asked a server and it answered. :D
fetch(url)asks a server and gives a promise of a reply.- Check
reply.okorreply.statusbefore you trust a reply. await reply.text()reads the reply's body.
new words in your collection
- server
- fetch
- status code
This lesson isn’t saved. A free account remembers every lesson you finish.