0

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.

  1. Process all delete actions, in order
  2. Process all add actions, in order
  3. 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.

Chris
  • 26,744
  • 48
  • 193
  • 345
  • 1
    Does http://stackoverflow.com/questions/25704745/how-do-i-sequentially-chain-promises-with-angularjs-q help? – Oleg Mar 13 '15 at 11:13
  • Looks great. Does the chain start executing straight away or do I have to execute it somehow? – Chris Mar 13 '15 at 11:58
  • It starts running immediately. Wrap it in a function and call it when necessary. – Oleg Mar 13 '15 at 12:03

0 Answers0