[英]$q.all with nested promise also created with $q.all
The following function tries to return a promise that will only resolve when all the async HTTP calls have finished: 以下函数尝试返回仅在所有异步HTTP调用完成后才能解决的Promise:
$scope.saveThat = function () {
var promises = [];
for (var i = 0; i < array.length; i++) {
var newPromise = $q.defer();
promises.push(newPromise);
// some more code...
(function (i, newPromise) {
$http(httpData)
.success(function (response) {
newPromise.resolve('Success');
})
.error(function (response) {
newPromise.reject('Error');
});
})(i, newPromise);
}
return $q.all(promises);
};
And the following snippet calls this function. 以下代码段调用了此函数。
// save this...
var promise1 = $rootScope.saveThis(result.Person);
promise1.then(function (success) {
}, function (error) {
saveErrorMessage += 'Error saving this: ' + error + '.';
});
// save that...
var promise2 = $rootScope.saveThat(result.Person);
promise3.then(function (success) {
}, function (error) {
saveErrorMessage += 'Error saving that: ' + error + '.';
});
// wait until all promises resolve
$q.all([promise1, promise2])
.then(
function (success) {
$scope.$emit(alertEvent.alert, { messages: 'Saved successfully!', alertType: alertEvent.type.success, close: true });
}, function (error) {
$scope.$emit(alertEvent.alert, { messages: saveErrorMessage, alertType: alertEvent.type.danger });
});
The problem I have is that the second promise ( $q.all([promise1, promise2])
) resolves even when the promises in promise2 haven't resolved yet. 我的问题是,即使promise2中的promise还没有解决,第二个promise(
$q.all([promise1, promise2])
)也会解决。
Because you are not creating an array of promise
, Actually it contains a $q.defer() object. 因为您没有创建
promise
数组,所以实际上它包含一个$ q.defer()对象。 You should be using 您应该使用
promises.push(newPromise.promise);
instead of 代替
promises.push(newPromise);
Also you need to avoid those anti-pattern, because you are creating $q
object unnecessarily as you have promise object there which returned from the $http.get
. 此外,您还需要避免使用这些反模式,因为您不必要在
$q
对象中创建$q
对象,而该对象从$http.get
返回。
Code 码
$scope.saveThat = function() {
var promises = [];
for (var i = 0; i < array.length; i++) {
// some more code...
var promise = $http(httpData)
.then(function(response) {
return 'Success'; //returning data from success resolves that promise with data
}, function(response) {
return 'Error'; //returning data from error reject that promise with data
});
promises.push(promise); //creating promise array
}
return $q.all(promises); //apply $q.all on promise array
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.