Why is the response object from JavaScript fetch API a promise?

If your question is “why does response.json() return a promise?” then @Bergi provides the clue in comments: “it waits for the body to load”.

If your question is “why isn’t response.json an attribute?”, then that would have required fetch to delay returning its response until the body had loaded, which might be OK for some, but not everyone.

This polyfill should get you what you want:

var fetchOk = api => fetch(api)
  .then(res => res.ok ? res : res.json().then(err => Promise.reject(err)));

then you can do:

fetchOk(API)
  .then(response => response.json())
  .catch(err => console.log(err));

The reverse cannot be polyfilled.

Leave a Comment