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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…