首页 文章

如果没有拒绝承诺连锁结果

提问于
浏览
2

我有一系列的承诺,我使用catch捕获错误 .

this.load()
    .then(self.initialize)
    .then(self.close)
    .catch(function(error){
        //error-handling
    })

如果链完成没有拒绝,会调用什么函数?我终于使用了,但是如果发生错误也会调用它 . 我想在catch函数之后调用一个函数,只有在没有承诺被拒绝的情况下才调用它 .

我正在将node.js与q - 模块一起使用 .

2 回答

  • 3

    我会将 .catch() 更改为 .then() 并提供onFullfill和onRejected处理程序 . 然后,您可以确切地确定发生了哪一个,并且您的代码非常清楚,一个或另一个将执行 .

    this.load()
        .then(self.initialize)
        .then(self.close)
        .then(function() {
             // success handling
         }, function(error){
            //error-handling
         });
    

    仅供参考,这不是唯一的做事方式 . 您也可以使用 .then(fn1).catch(fn2) ,类似地根据承诺状态先前的内容调用fn1或fn2,除非如果fn1返回被拒绝的承诺或抛出异常,则两者都可以被调用,因为这也将由fn2处理 .

  • 5

    添加另一个然后就可以了 .

    this.load()
        .then(self.initialize)
        .then(self.close)
        .then(function() {
          //Will be called if nothing is rejected
          //for sending response or so
        })
        .catch(function(error){
            //error-handling
        })
    

相关问题