简体   繁体   中英

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 .then s)

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

Make sure every call to a then() returns a value.

For eg

 var url = 'https://www.google.co.in'; var options = {}; var resolves = Promise.resolve(); resolves.then(() => { console.log('Resolved first promise'); var fetchPromise = fetch(url, options); fetchPromise.then(() => { console.log('Completed fetch'); }); }) .catch(error => { console.log('Error', error); });

Notice the console shows an uncaught exception. However, if you returned the inner promise (or any other value, which ends up turning into a promise via resolve ), you end up flattening the promise so exception bubble up.

 var url = 'https://www.google.co.in'; var options = {}; var resolves = Promise.resolve(); resolves.then(() => { console.log('Resolved first promise'); var fetchPromise = fetch(url, options); return fetchPromise.then(() => { console.log('Completed fetch'); }); }) .catch(error => { console.log('Error', error); });

Notice the exception bubbles up to the outer promise. Hope this clears up things a little bit.

Why not wrap it in a try / catch block, I have copied the following from ivo

function test() {
    return new Promise((resolve, reject) => {
        return reject('rejected');
    })};

(async ()=>{
    try{
        await test()
    }catch(er){
        console.log(er)
}})();

Promise rejections fall to the second param of the then function.

function test() {
    return new Promise((resolve, reject) => {
    return reject('rejected')
  })
}

test().then(function() {
  //here when you resolve
}, function(rej) {
  //here when you reject the promise
    console.log(rej)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM