0

I am writing a for loop which gets a JSON file using $http and assigns its content to an array index.

What basically happens is vm.newLanguages becomes an array of languages;

['Korean','English','Spanish']

And then the for loop loads a JSON file of language facts for each language and assigns them to vm.facts[i]...

korean-facts.JSON, english-facts.JSON, spanish-facts.JSON

That all works fine. However, within the GET request for the JSON files, the index of the for loop increases by 1, and I'm not 100% sure why. This means that the Korean facts are put into vm.facts[1] instead of vm.facts[0], English facts are put into vm.facts[2] and not vm.facts[1] etc.

Now, I can simply minus 1 of the index inside the for loop to solve the issue, but I'd like to know why the index increases in the for loop if possible.

Angular JS

$http.get('/ctrl/dashboard/get-new-languages.php').then(function(response){
        vm.newLanguages = JSON.parse(response.data.newLanguages);

        for(var i = 0; i < vm.newLanguages.length; i++){
            var item = vm.newLanguages[i];
            var facts;
            console.log(i); //this is correct (i)
            $http.get('/js/language-facts/' + item.toLowerCase() + '-facts.json').then(function(response){
                facts = response.data;
                console.log(i); //this is now i+1
                vm.facts[i] = facts;
            });
        };

    }) 
Chris Wickham
  • 521
  • 2
  • 5
  • 19

1 Answers1

0
$http.get('/js/language-facts/' + item.toLowerCase() + '-facts.json').then(function(response){
            facts = response.data;
            console.log(i); //this is now i+1
            vm.facts[i] = facts;
        });

is an asynchronous function and would output later when the loop has iterated, hence you print an updated value of i in the console.log() since the loop has moved on.

To get the expected behaviour you would have to wrap it in a closure check example

marvel308
  • 10,288
  • 1
  • 21
  • 32