Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to .catch a Promise.reject

I have a helper function for using fetch with CouchDB which ends as:

... return fetch(...)   .then(resp => resp.ok ? resp.json() : Promise.reject(resp))   .then(json => json.error ? Promise.reject(json) : json) 

and when I use it elsewhere, I was under the impression that I could .catch those explicit rejections:

  above_function(its_options)     .then(do_something)     .catch(err => do_something_with_the_json_error_rejection_or_resp_not_ok_rejection_or_the_above(err)) 

but alas, I can't seem to be able to get a hold of the rejections. The specific error I'm after is a HTTP 401 response.

What gives?

(Please note that there are implicit ES6 return's in the .thens)

like image 991
morbusg Avatar asked Sep 01 '17 18:09

morbusg


People also ask

How do I resolve a rejected Promise?

First, let us create a generic function that accepts a PokeAPI URL as argument and returns a Promise. If the API call is successful, a resolved promise is returned. A rejected promise is returned for any kind of errors. We will be using this function in several examples from now on to get a promise and work on it.

What happens if a Promise is rejected?

A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.

Do I need to return after rejecting a Promise?

The reject function of a Promise executor changes the state of the Promise , but does not stop the executor. In general, it is recommended to add a return statement after the reject to stop unintended code execution.

How do you reject a Promise then?

then(function(modifiedResource) { if (! isValid(modifiedResource)) { var validationError = getValidationError(modifiedResource); // fail promise with validationError } }) . catch(function() { // oh noes }); There's no longer a reference to the original resolve/reject function or the PromiseResolver.


1 Answers

    function test() {       return new Promise((resolve, reject) => {         return reject('rejected')       })     }      test().then(function() {       //here when you resolve     })     .catch(function(rej) {       //here when you reject the promise       console.log(rej);     });
like image 57
ivo Avatar answered Oct 19 '22 13:10

ivo