Monday, May 20, 2024
29
rated 0 times [  35] [ 6]  / answers: 1 / hits: 24609  / 9 Years ago, tue, september 22, 2015, 12:00:00

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?


More From » ecmascript-6

 Answers
7

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.


[#64962] Sunday, September 20, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daja

Total Points: 407
Total Questions: 103
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
daja questions
Tue, Dec 21, 21, 00:00, 2 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
Fri, Sep 6, 19, 00:00, 5 Years ago
Tue, Jul 23, 19, 00:00, 5 Years ago
;