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

promises chain result if nothing rejected

我有一个承诺链,我在其中使用 catch 来捕获错误。

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

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

我正在使用 node.js 和 q - 模块。

再添加一个即可。

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

我会将您的 .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 处理。