×

typescript · level 2 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.