Ho un'API HTTP che restituisce i dati JSON sia in caso di esito positivo che in caso di errore.recupero: Rifiuta promessa con oggetto errore JSON
Un fallimento esempio sarebbe simile a questa:
~ ◆ http get http://localhost:5000/api/isbn/2266202022
HTTP/1.1 400 BAD REQUEST
Content-Length: 171
Content-Type: application/json
Server: TornadoServer/4.0
{
"message": "There was an issue with at least some of the supplied values.",
"payload": {
"isbn": "Could not find match for ISBN."
},
"type": "validation"
}
Quello che voglio raggiungere nel mio codice JavaScript è qualcosa di simile:
fetch(url)
.then((resp) => {
if (resp.status >= 200 && resp.status < 300) {
return resp.json();
} else {
// This does not work, since the Promise returned by `json()` is never fulfilled
return Promise.reject(resp.json());
}
})
.catch((error) => {
// Do something with the error object
}
Vuoi dire 'metodo json' restituisce un' Promise'? – thefourtheye
Sì, secondo la specifica 'fetch' del gruppo di lavoro: https://fetch.spec.whatwg.org/#concept-body-consume-body – jbaiter