我需要创建链式 promise :
var deferred = $q.defer();
$timeout(function() {
deferred.reject({result: 'errror'});
}, 3000);
deferred.promise.then(angular.noop, function errorHandler(result) {
//some actions
return result;
}).then(function successCallback(result) {
console.log('what do I do here?');
return result;
}, function errorCallback(result) {
$scope.result= result;
return result;
});
如果我将 errorCallback 放入第一个 then
中,第二个 then
将被解析并调用其 successCallback 。但是如果我删除 errorHandler
那么第二个 promise 将被拒绝。
根据 Angular JS 文档,传播拒绝的唯一方法是返回 $q.reject();
它看起来并不明显,尤其是因为我必须注入(inject) $q
服务,即使不需要;
也可以通过在errorHandler
中抛出异常来完成,但是它会将异常跟踪写入控制台,这样不好。
是否有另一种选择以明确的方式做到这一点?原因是什么?为什么完成?在哪种情况下,当前行为可能有用?
最佳答案
And what the reason why it is done. In which case, the current behavior can be useful?
当您在 errorHandler 中尝试修复错误状态并以某种方式解决 promise 时,它会很有用。
var retriesCount = 0;
function doWork()
{
return $http.post('url')
.then(function(response){
// check success-property of returned data
if(response.data.success)
// just unwrap data from response, may be do some other manipulations
return response.data;
else
// reject with error
return $q.reject('some error occured');
})
.catch(function(reason){
if(retriesCount++ < 3)
// some error, let me try to recover myself once again
return doWork();
else
// mission failed... finally reject
return $q.reject(reason);
});
}
doWork().then(console.log, console.error);
关于javascript - Angularjs promise 拒绝链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18758058/