Lesson

Fetch JSON

The census lives at a URL. fetch asks for it. It does not finish instantly. It returns a Promise — a value that will arrive later.

await pauses this function until that value lands. The function must be marked async.

const response = await fetch("/api/profile");
const settler = await response.json();
// settler is { name: "Ada Lovelace", rank: "Settler", city: "Colonia" }

response.json() is also a Promise. That is why it needs await too. After that you have a normal object — and you can destructure it.

In the exercise use the relative URL /api/profile. Type it in the page. You do not need the editor.

I'm ready — try the exercise →