Why does .json() return a promise?

I’ve been messing around with the fetch() api recently, and noticed something which was a bit quirky.

let url = "http://jsonplaceholder.typicode.com/posts/6";

let iterator = fetch(url);

iterator
  .then(response => {
      return {
          data: response.json(),
          status: response.status
      }
  })
  .then(post => document.write(post.data));
;

post.data returns a Promise object.
http://jsbin.com/wofulo/2/edit?js,output

However if it is written as:

let url = "http://jsonplaceholder.typicode.com/posts/6";

let iterator = fetch(url);

iterator
  .then(response => response.json())
  .then(post => document.write(post.title));
;

post here is a standard Object which you can access the title attribute.
http://jsbin.com/wofulo/edit?js,output

So my question is: why does response.json return a promise in an object literal, but return the value if just returned?

6 Answers
6

Leave a Comment