【问题标题】:Why is the chained callback for success promises executed on both success and failure? [duplicate]为什么成功和失败都执行成功承诺的链式回调? [复制]
【发布时间】:2015-11-01 10:46:27
【问题描述】:

所以我有一个保存 Ember Data 模型的基本函数,并在失败时运行通用回调代码,然后将承诺返回给调用者,因此调用者可以自行链接其他回调,但不知何故,链接的回调 来自调用者未按预期执行,成功代码在失败和成功时执行,而失败代码从未执行

下面是通用函数的代码:

// this function returns the model.save() promise to allow chaining of promises on the caller scope.


   function baseCall() {

      return model.save().then(function () {
        //success
      }, function (reason) {
        //failure
        if (reason.errors) {
          model.set('errors', reason.errors);
        }
      });
    }  

这是调用者代码:

baseCall().then(function(post) {
        console.log('super.success');//runs on failure AND success
      }, function() {
        console.log('super.failure');//never runs
      });

【问题讨论】:

  • 如果您想使用拒绝功能,只需 throw new Error(reason)。见chaining
  • this function returns the model.save() promise - 这是不正确的。 baseCallthen 块中返回成功或失败函数的“结果”——如所写,成功/失败都将导致解析值未定义——当然,可能有代码你没有显示,否则baseCall 函数完全没有意义
  • @Bergi 有一个 huge 问题,我认为已经有一个规范或简短的问题。
  • @BenjaminGruenbaum:是的,你是对的,这个问题不是最好或最简洁的问题。过去我已经将它用作规范的骗子,因为我的答案包含一个加长的解释:-) 也许我们应该完善它,或者使用完全不同的一个 - 只是告诉我它。
  • @Bergi 只是做一个规范?问这个问题,把你的答案移到那里,然后把这个投票给那个。这些绝对值得您明智地代表您,并且比大多数其他问题更有帮助。其他规范的候选人可以被重定向到那里。

标签: javascript ember.js ember-data promise rsvp.js


【解决方案1】:

出于同样的原因,下面的代码总是提示“Hello”;

try {
     model.save(); // throws Error
} catch (e) {
    if (reason.errors) {
      model.set('errors', reason.errors);
    }
}
console.log("Hello");

promise 错误处理程序,如同步 catch“处理”错误。如果您不想将错误标记为已处理 - 重新抛出它:

 throw reason; // always throw proper `Error`s

【讨论】:

  • 在做出这样的假设之前,我应该已经了解了 Promise 的工作原理。有道理,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多