0

I've stumbled on this several times, and cannot seem to find a good solution:

for (var i = types.length - 1; i >= 0; i--) {
    api.get("test").then(function(res){
        // do something with i here
        $scope.var[i] = res;
    });
};

When the then() function is triggered the iteration is already done, resulting only $scope.var[0] is being used, instead of $scope.var[1], $scope.var[2] etc.

All I can think of is either giving the i variable as argument to the function and return it with the deferred or using callbacks, but neither is really nice. Is there a solution for this?

user3136936
  • 311
  • 3
  • 11

1 Answers1

1

One way is to wrap it in an anonymous function to force i to bind to the iterating value:

for (var i = types.length - 1; i >= 0; i--) {
    (function (actual_i) {
        api.get("test").then(function(res){
            // do something with i here
            $scope.var[actual_i] = res;
        });
    }(i));
};

Since you're looping over an array using the map function with a callback will give you the binding for free:

types.map(function (value, i) {
    api.get("test").then(function(res){
        // do something with i here
        $scope.var[i] = res;
    });
});
Halcyon
  • 57,230
  • 10
  • 89
  • 128