0

I've got loop function with promises:

for (var a in $scope.atrakcje) {
  if ($scope.atrakcje[a].x && $scope.atrakcje[a].y) {
    App.countDistance($scope.atrakcje[a].x, $scope.atrakcje[a].y).then(function(km) {
      $scope.atrakcje[a].distance = km;
    });
  }
}

The problem with this loop is that all km values are assigned to the last $scope.atrakcje element. It should assign the first promise to the first element, the second to the second and so on. How to do it?

Anders Ekdahl
  • 22,685
  • 4
  • 70
  • 59
piernik
  • 3,507
  • 3
  • 42
  • 84
  • 1
    This solves your problem http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue –  Mar 19 '14 at 12:29
  • possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Bergi Mar 19 '14 at 15:36

2 Answers2

3

Try:

for (var a in $scope.atrakcje) {
  if ($scope.atrakcje[a].x && $scope.atrakcje[a].y) {
    (function(index) {
      App.countDistance($scope.atrakcje[index].x, $scope.atrakcje[index].y).then(function(km) {
        $scope.atrakcje[index].distance = km;
      });
    })(a);
  }
}
0

The problem here is that your then function is called after the for loop is finished, which means that when the promise is resolved, the a variable will contain the last key from $scope.atrakcje. Create a closure around it to capture the value of the key, something like:

Object.keys($scope.atrakcje).forEach(function(a) {
  if ($scope.atrakcje[a].x && $scope.atrakcje[a].y) {
    App.countDistance($scope.atrakcje[a].x, $scope.atrakcje[a].y).then(function(km) {
      $scope.atrakcje[a].distance = km;
    });
  }
});
Anders Ekdahl
  • 22,685
  • 4
  • 70
  • 59