1

I have this piece of code in JS as described below

for (id in ids) {
    if (id needs to be called) {
        console.log(id);  // statement 1
        $http.post('someEndpoint', {id : id}).then(function success(response) {
            console.log(id);  // statement 2
            someDataStructure[id].data = response.data;
        });
    }
}

Assuming ids = [1, 2, 3], at statement 1, 1 2 3 is printed on the console. At statement 2, 3 3 3 is printed. This is obviously less than ideal and I am losing data for 1 2. Also, I must add that the endpoint is getting requests for 1 2 3, so at this point, I am really confused. It would be great if someone could throw some light and help me understand how to fix this.

pratnala
  • 3,723
  • 7
  • 35
  • 58
  • If `ids` is an array, use `for (let index in ids)`, and then `let id = ids[index]`. – 6324 Jul 29 '16 at 19:49
  • 1
    If `ids` is an array, you shouldn't be using `for-in`. Change it to `ids.forEach(function(id) { ... })` and you're set. –  Jul 29 '16 at 19:52
  • @squint Yeah, I know that issue, that's why I said "make sure to call the `id`, not index of `id`. To avoid confusion, I modified my answer. Using ES6 `let`, we can get rid of closures. – 6324 Jul 29 '16 at 19:54

1 Answers1

2

Wrap id in a closure function:

for (id in ids) {
    (function(id) {
        if (id needs to be called) {
            console.log(id);  // statement 1
            $http.post('someEndpoint', {id : id}).then(function success(response) {
                console.log(id);  // statement 2
                someDataStructure[id].data = response.data;
            });
        }
    })(id);
}

You could also simply use a forEach loop, which will automatically make the closure:

ids.forEach(function(id) {
    if (/*id needs to be called*/) {
        console.log(id);  // statement 1
        $http.post('someEndpoint', {id : id}).then(function success(response) {
            console.log(id);  // statement 2
            someDataStructure[id].data = response.data;
        });
    }
});
Community
  • 1
  • 1
Blue
  • 22,608
  • 7
  • 62
  • 92