Javascript Fetch Api - Why Does Response. Json() Return a Promise Object (Instead of Json)? [Duplicate]

Javascript Fetch Api - Why Does Response. Json() Return a Promise Object (Instead of Json)? [Duplicate]

I've just started to learn the Fetch API:

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

fetch(')
  .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.

2

1 Answer

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

4
Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.