4

I have this code:

fetch(url).then(response => {
  const json = response.json();
  console.log('simplest possible fetch', json, json.where);
});

In the console I get:

simplest possible fetch Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} undefined

I get this most of the time. Sometimes I get the "success" status. To me this implies the callback is being run before the fetch promise has resolved.

I want the function to be run only when the fetch completes. How do I do this?

alexmac
  • 19,087
  • 7
  • 58
  • 69
Shoreline
  • 798
  • 1
  • 9
  • 26

1 Answers1

12

response.json() returns a promise, use then callback to get the data:

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

fetch(url)
  .then(response => response.json())
  .then(data => console.log('simplest possible fetch', data, data.where));
alexmac
  • 19,087
  • 7
  • 58
  • 69