Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  100] [ 1]  / answers: 1 / hits: 67253  / 9 Years ago, mon, april 6, 2015, 12:00:00

I have an HTTP API that returns JSON data both on success and on failure.



An example failure would look like this:



~ ◆ 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
}


What I want to achieve in my JavaScript code is something like this:



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
}

More From » promise

 Answers
134

 // This does not work, since the Promise returned by `json()` is never fulfilled
return Promise.reject(resp.json());



Well, the resp.json promise will be fulfilled, only Promise.reject doesn't wait for it and immediately rejects with a promise.



I'll assume that you rather want to do the following:



fetch(url).then((resp) => {
let json = resp.json(); // there's always a body
if (resp.status >= 200 && resp.status < 300) {
return json;
} else {
return json.then(Promise.reject.bind(Promise));
}
})


(or, written explicitly)



    return json.then(err => {throw err;});

[#67185] Thursday, April 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
;