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?

2

2 Answers 2

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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;
    });
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.