【问题标题】:AngularJS chained promises and finally callbackAngularJS 链式承诺和最终回调
【发布时间】:2016-06-18 07:36:16
【问题描述】:

所以我有 2 个 promise 函数。当第一个函数出现错误时,我希望它显示错误消息。当完成或失败时,我希望他们执行 finally 捕获所有函数,但由于某种原因它不起作用。 我的代码如下所示:

// If our garment has a logo
shared.logoExists(garment, model).then(function () {

    // Save our panel
    return shared.save(model);

// If there was an error
}, function () {

    // Display an error message
    toastr.warning(localization.resource.logoPlacementError.message);

// Always close the library
}).finally(function () {

    // Reset our attachments
    self.resetAttachment();

    // Hide our library
    self.closeLibrary();
});

所以基本上我想要实现的是,如果第一个函数失败,它将显示并出错。 当第二个函数失败时,它不会做任何事情。 但无论成功或失败,它都会关闭库。

有谁知道我如何做到这一点?

【问题讨论】:

  • 我喜欢这个问题 - 实际上我正在构建它
  • 什么不起作用?是否抛出任何错误?

标签: angularjs


【解决方案1】:

关闭then函数后必须使用.catch:

// If our garment has a logo
shared.logoExists(garment, model).then(function () {

    // Save our panel
    return shared.save(model);

// If there was an error
}).catch(function () {

    // Display an error message
    toastr.warning(localization.resource.logoPlacementError.message);

// Always close the library
}).finally(function () {

    // Reset our attachments
    self.resetAttachment();

    // Hide our library
    self.closeLibrary();
});

【讨论】:

  • 没有解释为什么“你必须使用 catch”catch 没有返回任何内容,所以实际上这里没有太大的有效区别
  • promise 模式的结构可能导致 finally 函数不被调用。只是想尝试一些东西。而且他的代码的结构方式是,他希望能够识别是否存在错误,因此使用了 catch 函数。
  • “你必须使用”和... “试试这个”之间的巨大区别。使用 catch 代替 then 的第二个参数有很好的支持性论据,但这里没有提及
  • 那么请随意提供。
【解决方案2】:

根据您使用的 Angular 版本,您可能必须使用“always”而不是“finally”。尝试“总是”,看看它是否有效。

How to always run some code when a promise is fulfilled in Angular.js

【讨论】:

    【解决方案3】:

    事实证明,我的方法很好。 logoExists 函数没有在所有应有的地方解决/拒绝承诺。当我解决这个问题时,我上面的代码就可以工作了。

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 2013-07-22
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2013-09-16
      相关资源
      最近更新 更多