我有一个简单的 angularjs 服务,它封装了 breeze 以供我的应用程序使用。在这项服务中,我希望有一个单一的机制来处理失败。我试图在调用结束时将 .fail() 链接起来,如果 breeze 调用失败(例如由于用户注销),则会调用失败。唯一的问题是链中的第一个 .done() (通常驻留在调用服务的 Controller 中)也被调用。我只希望在 Breeze 成功时调用它。
如何防止第一个 done 也被调用?
以下是一个示例保存调用(带有错误调用的 done)
dataStore.saveEntity(model)
.then(function() {
// This is being called on fail
});
还有一小段服务包装 Breeze
angular.module('app')
.factory('dataStore' ,function() {
var _handleFail = function(error) {
if (error && error.status && error.status === 401) {
// Logged out error (for example
}
};
function saveEntity(entity) {
return manager.saveChanges(entity).fail(_handleFail);
}
最佳答案
事实证明 .fail() 进一步传播了 promise 。请考虑以下事项:
promise.then(function(){
console.log('Then 1');
throw new Error('Error');
})
.then(function(){
console.log('Then 2');
})
.then(function(){
console.log('Then 3');
})
.fail(function(){
console.log('Fail 1');
})
.then(function(){
console.log('Then 4');
});
将输出:
> Then 1
> Fail 1
> Then 4
.fail() 从第一个 .then() 捕获错误,然后将 promise 传递给第四个 .then()。在我的示例中,breeze 查询生成一个错误,该错误被 .fail() 捕获,处理后将 promise 传递给调用容器内的 .then()。
要解决此问题,_handleFail() 函数需要抛出一个错误以防止任何链式 .then() 被调用(直到错误再次由 .fail() 处理。
所以我的服务现在看起来像:
angular.module('app') .factory('dataStore' ,function() {
var _handleFail = function(error) {
if (error && error.status && error.status === 401) {
// Logged out error (for example
throw new Error('Unauthorized');
}
};
function saveEntity(entity) {
return manager.saveChanges(entity).fail(_handleFail);
}
关于javascript - 处理失败的 breezejs 保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18859578/