所以我有这段代码:
var deferred = $q.defer();
var promises = [];
angular.forEach($scope.devices, function(device){
var promise = memberService.InsertDevice(memberId, device).then(function (data) {
//device inserted
}, function (rejectData) {
if (rejectData.Error == "Cannot insert record since it already exists") {
alert("The number " + device.PhoneNumber + " already exists. Try with a different number.");
}
});
promises.push(promise);
});
$q.all(promises).then(function (data) {
//perform something on Success
}, function (data) {
//perform something on rejection
//THIS NEVER GETS CALLED EVEN IF I GET THE ALERT FROM THE TOP
});
查看最后一条评论。出于某种原因,即使我收到警报(意味着其中一个调用出现问题),也不会调用整体拒绝。
答案 0 :(得分:1)
Promise提供了在您的失败中“恢复”的机会,因此您必须在$q.all
的错误句柄中返回拒绝,以确定它实际上已失败。以下代码中的唯一增量为return $q.reject(rejectData);
var deferred = $q.defer();
var promises = [];
angular.forEach($scope.devices, function(device){
var promise = memberService.InsertDevice(memberId, device).then(function (data) {
//device inserted
}, function (rejectData) {
if (rejectData.Error == "Cannot insert record since it already exists") {
alert("The number " + device.PhoneNumber + " already exists. Try with a different number.");
}
return $q.reject(rejectData);
});
promises.push(promise);
});
$q.all(promises).then(function (data) {
//perform something on Success
}, function (data) {
//perform something on rejection
//THIS NEVER GETS CALLED EVEN IF I GET THE ALERT FROM THE TOP
});