我是AngularJs的新手。 我有一个验证函数,它返回了promise。此函数在内部调用http get api并接收promise响应。我有一些验证码需要来自被叫api的响应。但是在http调用完成并且函数从api接收响应之前,validate函数会向调用者返回promise。这导致验证失败。有人可以分享一些满足这个要求的代码。
function validateDates(delegate) {
var currStartDate = delegate.start_date;
var currEndDate = delegate.end_date;
var overlap = false;
var deferred = $q.defer();
UserDelegateService.getDelegateForUser(delegate.comit_id).then(
function(res) {
for(var i = 0; i<res.length; i++) {
var sDate = $filter('date')(res[i].start_date, 'yyyy-MM-dd');
var eDate = $filter('date')(res[i].end_date, 'yyyy-MM-dd');
if(currStartDate <= eDate && sDate <= currEndDate) {
overlap = true;
deferred.resolve(overlap);
} else
deferred.reject("Not overlapping");
}
},
function(errorresponse) {
console.log(errorresponse);
});
return deferred.promise;
};
调用代码:
$scope.saveDelegate = function() {
var delegate = {
//assign values ...
};
var promise = validateDates(delegate);
promise.then(function(data) {
if(data) {
console.log('Dates are overlapping....if part.......', data);
}
}, function(reason) {
console.log('Dates are not overlapping..saving datlegate..else part.........', reason);
$scope.save(delegate);
});
};
答案 0 :(得分:0)
使用$q.defer
会破坏承诺链并丢失错误信息。此外,正在对for
循环的第一项进行解决/拒绝决定。
而是返回值和链。
function validateDates(delegate) {
var currStartDate = delegate.start_date;
var currEndDate = delegate.end_date;
//var overlap = false;
//var deferred = $q.defer();
var p = UserDelegateService.getDelegateForUser(delegate.comit_id);
var derivedPromise = p.then(
function onSuccess(res) {
//Initialize overlap var in success handler
var overlap = false;
for(var i = 0; i<res.length; i++) {
var sDate = $filter('date')(res[i].start_date, 'yyyy-MM-dd');
var eDate = $filter('date')(res[i].end_date, 'yyyy-MM-dd');
if(currStartDate <= eDate && sDate <= currEndDate) {
overlap = true;
};
//Return value of overlap for chaining
return overlap;
});
};
//return derived promise
return derivedPromise;
};
如果任何日期重叠,则上述函数返回一个解析true
的承诺,如果没有任何日期重叠,则会解析false
。
客户代码:
$scope.saveDelegate = function() {
var delegate = {
//assign values ...
};
var promise = validateDates(delegate);
promise.then(function onSuccess(overlap) {
if(overlap) {
console.log('Dates are overlapping....if part.......', overlap);
} else {
console.log('Dates are not overlapping..saving datlegate..');
$scope.save(delegate);
};
}).catch(function onReject(reason) {
console.log("Promise rejected for another reason");
});
};
通过返回和链接承诺,getDelegateForUser
操作中的任何错误都会转发到客户端代码。