【发布时间】: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- 这是不正确的。baseCall在then块中返回成功或失败函数的“结果”——如所写,成功/失败都将导致解析值未定义——当然,可能有代码你没有显示,否则baseCall函数完全没有意义 -
@Bergi 有一个 huge 问题,我认为已经有一个规范或简短的问题。
-
@BenjaminGruenbaum:是的,你是对的,这个问题不是最好或最简洁的问题。过去我已经将它用作规范的骗子,因为我的答案包含一个加长的解释:-) 也许我们应该完善它,或者使用完全不同的一个 - 只是告诉我它。
-
@Bergi 只是做一个规范?问这个问题,把你的答案移到那里,然后把这个投票给那个。这些绝对值得您明智地代表您,并且比大多数其他问题更有帮助。其他规范的候选人可以被重定向到那里。
标签: javascript ember.js ember-data promise rsvp.js