How to .catch a Promise.reject

坚强是说给别人听的谎言 提交于 2019-12-01 13:45:52

问题


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)


回答1:


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



回答2:


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

For e.g.

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.




回答3:


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


来源:https://stackoverflow.com/questions/46005954/how-to-catch-a-promise-reject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!