I have written Saving code for a controller. The amount of work is variable and can either be a delete
,add
or edit
action. I want them to be done in that specific order so would like to, somehow, create a promise chain that does each action after the other i.e.
- Process all
delete
actions, in order - Process all
add
actions, in order - Process all
edit
actions, in order
Currently my code looks like this
// Save deleted groups first
angular.forEach(listOfDeletedGroups, $scope.saveGroupDelete);
// Now save added groups
angular.forEach(listOfAddedGroups, $scope.saveGroupAdd);
// Now save any edits
angular.forEach(listOfChangedGroups, $scope.saveGroupEdits);
My save methods are all very similar, and look like this:
$scope.saveGroupDelete = function (group) {
groupAPIService.deleteGroup(group)
.success(function () {
})
.error(function () {
$scope.savingInfo.numErrors++;
})
.finally(function () {
$scope.savingActionComplete(group);
});
};
I know I can use $q
to make these functions return promises that I could use with .then()
$scope.saveGroupDelete = function (group) {
var deferred = $q.defer();
groupAPIService.deleteGroup(group)
.success(function () {
})
.error(function () {
$scope.savingInfo.numErrors++;
})
.finally(function () {
$scope.savingActionComplete(group);
deferred.resolve();
});
return deferred.promise;
};
But I dont know how I can chain up these requests to ensure they happen in order, one after each other for N promises.