amb amb - 2 years ago 92
Javascript Question

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

When requesting from a server with JavaScript fetch API, you have to do something like

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

is resolving its promise.

The thing is that if you want to catch
's errors, you have to resolve the response promise and then reject the fetch promise, because you'll only end in
if there's been a network error. So the fetch call becomes something like

.then(response => response.ok ? response.json() : response.json().then(err => Promise.reject(err)))
.catch(err => console.log(err))

This is something much harder to read and reason about. So my question is: why is this needed? What's the point of having a promise as a response value? Are there any better ways to handle this?

jib jib
Answer Source

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 fetchBody = api => fetch(api)
  .then(res => res.ok ? res : res.json().then(err => Promise.reject(err)));

then you can do:

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

The reverse cannot be polyfilled.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download