Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

Here, response.json() is resolving its promise.

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

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

like image 542
amb Avatar asked Sep 22 '15 16:09

amb


People also ask

Is JavaScript fetch a Promise?

Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

Does fetch method always return a Promise?

fetch() The global fetch() method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available.

What is the difference between fetch and Promise?

Fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

What is response object in JavaScript?

The Response interface of the Fetch API represents the response to a request. You can create a new Response object using the Response() constructor, but you are more likely to encounter a Response object being returned as the result of another API operation—for example, a service worker FetchEvent.


1 Answers

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.

like image 152
jib Avatar answered Sep 27 '22 21:09

jib