如何.catch Promise.reject [英] How to .catch a Promise.reject

查看:168
本文介绍了如何.catch Promise.reject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个帮助函数,用于使用CouchDB fetch ,结束为:

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)

和当我在其他地方使用它时,我的印象是我可以 .catch 那些明确的拒绝:

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

但是,唉,我似乎无法控制拒绝。
我之后的具体错误是HTTP 401响应。

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.

什么给出?

(请注意, .then 中隐含的ES6 返回

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

推荐答案

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

这篇关于如何.catch Promise.reject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆