为什么在成功和失败时都执行成功承诺的链式回调?
Why is the chained callback for success promises executed on both success and failure?
所以我有一个保存 Ember 数据模型的基本函数,并在失败时运行通用回调代码,然后 returns 向调用者承诺,因此调用者可以在其上链接其他回调自己的,但不知何故,来自调用者的链式回调没有按预期执行,成功代码在失败和成功时执行,而失败代码永远不会执行
这是常用函数的代码:
// 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
});
出于同样的原因,以下代码总是提醒 "Hello";
try {
model.save(); // throws Error
} catch (e) {
if (reason.errors) {
model.set('errors', reason.errors);
}
}
console.log("Hello");
一个 promise 错误处理程序,如同步 catch
"handles" 错误。如果您不想将错误标记为已处理 - 重新抛出它:
throw reason; // always throw proper `Error`s
所以我有一个保存 Ember 数据模型的基本函数,并在失败时运行通用回调代码,然后 returns 向调用者承诺,因此调用者可以在其上链接其他回调自己的,但不知何故,来自调用者的链式回调没有按预期执行,成功代码在失败和成功时执行,而失败代码永远不会执行
这是常用函数的代码:
// 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
});
出于同样的原因,以下代码总是提醒 "Hello";
try {
model.save(); // throws Error
} catch (e) {
if (reason.errors) {
model.set('errors', reason.errors);
}
}
console.log("Hello");
一个 promise 错误处理程序,如同步 catch
"handles" 错误。如果您不想将错误标记为已处理 - 重新抛出它:
throw reason; // always throw proper `Error`s