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 .then
s)
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.
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.
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.
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With