0

I am try to call function $scope.getThisFunction($scope.Num) after completion of for loop, i tried below code but not working. Any suggestion?

for(var i = 0; i < $scope.selection.length; i++) {                
    $http({
        method: "POST",
        url: '/url/' + $scope.Num + '/' + $scope.selection[i]
    }).then(function mySucces(response) {
        if(i == $scope.selection.length - 1) {  
           $scope.getThisFunction($scope.Num); //not working
        }
    }, function myError(response) {
        alert("SORRY, SOME TECHNICAL ERROR OCCUR");
    });
}
Mistalis
  • 17,793
  • 13
  • 73
  • 97
Pratyush Pranjal
  • 544
  • 6
  • 26
  • 4
    It is not a very good idea to make HTTP posts in a for-loop. You should rewrite your API to accept several `selections` in one unique call. – Mistalis Mar 07 '17 at 13:10
  • @Pratyush Pranjal You want the `$scope.getThisFunction($scope.Num)` to be called in the last element of the loop or in the last response of your posts? If you want it to be called when the last post responds try using promises(`$q.all`) – Paraíso Mar 07 '17 at 13:23
  • Duplicate of http://stackoverflow.com/questions/21310964/angularjs-q-all – Gaurav Kumar Singh Mar 07 '17 at 13:24

2 Answers2

1

make separate function and use http request inside that function. Because when for loop looping around it refer the same reference. Even though it create new closure it has the same reference. so it's only taken the last index of for loop

for (var i = 0; i < $scope.selection.length; i++) {
    sendReq(i)
};

function sendReq(i) {
    $http({
        method: "POST",
        url: '/url/' + $scope.Num + '/' + $scope.selection[i]
    }).then(function mySucces(response) {
        if (i == $scope.selection.length - 1) {
            $scope.getThisFunction($scope.Num); //not working
        }
    }, function myError(response) {
        alert("SORRY, SOME TECHNICAL ERROR OCCUR");
    });
}
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
1

I'm not really sure what you're trying to accomplish. In your example you'd have to use

if (i === $scope.selection.length)

but that will fire multiple times, as the condition should most likely always be true when each promise resolves.

You should use $q.all and pass it an array of promises. $q is an angular service and you simply need to inject it.

Untested:

var promises = []

for (var i = 0; i < $scope.selection.length; i++) {
  promises.push($http({
    method: 'POST',
    url: '/url/' + $scope.Num + '/' + $scope.selection[i]
  });
}

$q.all(promises).then(function() {
  $scope.getThisFunction($scope.Num);
}, function() {
  alert('Error')
});

Edit:

I saw you accepted another answer. Let me that it would be easier to just keep your code and replace var by let instead of using a function closure. That would of course only work if you're working in an ES6 environment.

for(let i = 0; i < $scope.selection.length; i++)
  ...
gerrit
  • 391
  • 3
  • 11