【问题标题】:promises chain result if nothing rejected如果没有被拒绝,则承诺链结果
【发布时间】:2015-12-17 20:03:32
【问题描述】:

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

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

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

我正在使用带有 q - 模块的 node.js。

【问题讨论】:

    标签: javascript node.js promise angular-promise


    【解决方案1】:

    再添加一个即可。

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

    【讨论】:

    • 感谢 jfriend00 和 Mannu,这两个答案都有效。谢谢很多:)
    【解决方案2】:

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

    【讨论】:

    • 只有一个或另一个? Not exactly
    • @Bergi - 据我所知,我的第一个例子是“一个或另一个”。如果fn1 抛出或返回被拒绝的承诺,则第二个示例可能是两者。
    • 是的,是你措辞中的“和”让我很生气。
    猜你喜欢
    • 2016-08-03
    • 1970-01-01
    • 2019-11-25
    • 2013-09-16
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2018-05-09
    相关资源
    最近更新 更多