How to .catch a Promise.reject

morbusg picture morbusg · Sep 1, 2017 · Viewed 37.8k times · Source

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)

Answer

ivo picture ivo · Sep 1, 2017

    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);
    });