ThatBrianDude
ThatBrianDude

Reputation: 3190

Javascript: Reject a successful promise

Sometimes I find myself writing the following code:

if (result.status == 200) {
    return result.json()
} else {
    return result.json().then(res => Promise.reject(res))
}

If the status is any other than 200 then the result will contain an error message which I would like to return. (This is part of a api.js script)

Is there a better way to "inverse" the .json() promise?

I thought of maybe something like this:

return Promise.reject(result.json)

Is there a way for me to do something like that? I am expecting the successful result of result.json to be the error object in the catch route.

Upvotes: 2

Views: 183

Answers (2)

fifoq
fifoq

Reputation: 203

return result.json().then(res=>{
  if(result.state!==200) return Promise.reject(res);
  return res;
});

In my case I prefer the Promise.reject

info: Promise.reject vs throw Error

Upvotes: 0

libik
libik

Reputation: 23029

Well this looks a little weird, I would go with this approach

return result.json().then(json => {
   if (result.status === 200) {
      return json;
   }

   throw new Error(`Failed with ${json}`);
});
  • You should always throw/return rejected promises with Error objects inside. Some modules are even counting on that and can behave unexpectably with throwing non-error object
  • I think the throwing error is more "obvious" then returning something that behaves as throwing error
  • if-else is increasing complexity. Remove else if not necessary
  • It is better to get used to ===, using == can bring some issues

Upvotes: 1

Related Questions