0

I have 4 functions, calculateSingle, calculateAll, process and save.

process calls a service which saves my recalculated values and should always happen after calculateAll has finished. This doesn't happen in my case. Somehow save decides to run even about 4ms before all the calculateSingle calls do.

This is my approach. I pass the save function as a callback to the calculateAll function. Please consider this pseudo code I've written.

$scope.calculateSingle = function() {
  //call web service to calculate single row in a table
}

$scope.calculateAll = function(callback) {
  var promises = [];

  for(var i in numberOfRows) {
    promises.push($scope.calculateSingle(i));
  }

  //combine promises to call calculateSingle as many times as there are rows
  $q.all(promises).then(
    function successCallback(response) {
      //take the response and apply all the recalculated values onto view
    }
  ).then(
    //SHOULD BE CALLED AFTER CALCULATE IS FINISHED AND VALUES ARE REASSIGNED
    //This is the $scope.save() function passes as a callback function
    if(callback) {
      callback();
    }
  );
}

$scope.process = function() {
  $scope.calculateAll($scope.save());
}

$scope.save = function() {
  //run the save
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
LazioTibijczyk
  • 1,701
  • 21
  • 48

1 Answers1

3

$scope.save() calls save immediately; if you want to pass it as a callback, you should use $scope.save

$scope.process = function() {
  $scope.calculateAll($scope.save);
}
Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80