Reputation: 1077
Hi I am struggling to understand Angular deffering and promises. I would like to know when all promises have been completed so i can hide a "loading" message. So here is my code example:
$scope.buildTeam = function () {
$scope.Message = "loading...";
var deferred = $q.defer();
var promiseList = [];
c = $scope.teamModels[0];
for (index = 0; index < c.quantity; ++index) {
var assignment = new teamAssignment(c.assignmentTypeId, $scope.parentAssignment.AssignmentId, c.description);
promiseList.push(departmentService.addAssignment(assignment).then(function (result) {
//added lead/captain. Now insert visually on page
insertToScope($scope, result);
}));
}
}
$q.all(promiseList).then(function () {
deferred.resolve();
$scope.Message = "Loaded.";
});
}
The problem is Have is that $scope.Message shows "Loaded" well before the data has been inserted onto the page in the case of a large data pull. Could it be that i also need to defer insertToScope? InsertToScope simply reads:
function insertToScope($scope, a) {
//get root scope
var rs = angular.element("#ngRootContainer").scope();
rs.parentAssig.push(a);
}
And the department service looks like this:
departmentModule.factory('departmentService', function ($http, $q) {
return {
addAssignment: function(assignment){
var deferred = $q.defer();
$http.post('/Department/addAssignmentReturnAssignmentRow', assignment).success(deferred.resolve).error(deferred.reject);
return deferred.promise;
}
});
So my question is, what do i need to do to call a function only after all the promises are done? Thank you in advance for your feedback.
Upvotes: 0
Views: 262
Reputation: 6066
$q.all
should do what you need. If your code doesn't work, I see two options:
promiseList
that does not contain all promises you want to wait for. Debug your code and check that all promises are passed in. Make sure it's an array you pass as the first parameter.insertToScope
, and 'B' in the then
of your $q.all
, you should see A ... A B
in the console.
Here is a simple plunkr that shows how to use $q.all()
: http://plnkr.co/edit/9QH9Y0w7DG0WCouMuX82?p=preview
Upvotes: 1