Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript fetch API - Why does response.json() return a promise object (instead of JSON)? [duplicate]

I've just started to learn the Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Here's a code snippet which I wrote to tinker around with it:

fetch('http://swapi.co/api/people/1')
  .then(function(response) {
    var json = response.json();

    console.log(json);
    // Expected : { "name": "Luke Skywalker","height": "1.72 m", ... } 
    // Get : Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
  }); 

I would have expected to get an JSON object out of response.json().

Similar to what you get when using JSON.parse().

Instead I get a promise object.

If I enlarge the promise chain like shown here ...

return response.json().then(function(json) {
      // process your JSON further
});

... then it works: Within the then method of the following promise it appears as json.

Why can't I retrieve the JSON data within the then() of the first promise?

Can anyone please explain what is going on here?

I would really much appreciate it.

like image 436
cluster1 Avatar asked Sep 11 '16 12:09

cluster1


People also ask

Why does fetch json return a Promise?

json return a promise? Because you receive the response as soon as all headers have arrived. Calling . json() gets you another promise for the body of the http response that is yet to be loaded.

Does response json return Promise?

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

Does fetch API return a Promise?

fetch() starts a request and returns a promise. When the request completes, the promise is resolved with the Response object. If the request fails due to some network problems, the promise is rejected.

How do I get json from fetch response?

To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.


1 Answers

because response.json() returns another promise (which is within your function body)

https://developer.mozilla.org/en-US/docs/Web/API/Body/json

like image 137
dee zg Avatar answered Sep 24 '22 21:09

dee zg