1

I'm doing a loop like this :

for (var index in data) 
{
    console.log(index);    
    $http.post('server.php')
    .success(function(data, status) 
    { 
        console.log(index); 
    }
}

The first console.log() displays : 0,1,2,3,4,5

The second console.log() displays : 5,5,5,5,5,5

And I have really no idea why. Is it because of the fact that i'm using 2 variables named data ? I tried renaming one, but it didn't fixed the issue.

  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Nikhilesh K V Apr 25 '16 at 12:47
  • @NikhileshKV Possibly, but the question must be a question, the link you proposed assumes the user knows what to look for. – SparK Apr 25 '16 at 12:53

3 Answers3

1

Use Closures, The function defined in the closure 'remembers' the environment in which it was created. [From docs]

for (var index in data) {
  (function(index) {
    $http.post('server.php')
      .success(function(data, status) {
        console.log(index);
      });
  })(index);
}
Rayon
  • 36,219
  • 4
  • 49
  • 76
1

You need to use Closures in this aspect. The closure, "packs" the value of the index, while it gets executed at a callback, later.

for (var index in data) {
  (function(index) {
    $http.post('server.php')
    .success(function(data, status) {
      console.log(index);
    });
  })(index);
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Closure. If it's hard to understand it's basically doing this:

function doPostCall(index) {
    $http.post('server.php')
    .success(function(data, status) { 
        console.log(index); 
    }
}

for (var index in data) {
    console.log(index);    
    doPostCall(index)
}

See, it's just separating the post into it's own function with it's own index variable that is guaranteed to not change from outside/

Martin Gottweis
  • 2,721
  • 13
  • 27