Fetch and APIs: Getting Real Data Into Your Page Your First Request
1 / 5
Next
Your First Request ~15min

fetch returns a promise

A network request takes time, so fetch does not return the data. It returns a promise. An object that says "I will have an answer later".

fetch(url)
  .then(function (response) { return response.json(); })
  .then(function (data) { console.log(data); });

Why two .then calls

The first gives you the response. Status, headers, and a body that has not been read yet. response.json() reads and parses that body, and it is ALSO asynchronous, so it returns another promise. Hence the second .then.

Forgetting the second one is why people log a Response object and wonder where their data went.

Tasks
Preview