Xiaofan Wu Xiaofan Wu - 3 months ago 6
AngularJS Question

Query inside of a for loop is not functioning correctly

I have a list of

alumId
s that I want to pass in to firebase query and retrieve information base the ids. Right now, I am facing a bug that the for loop is not looping correctly.

Expected result will be:


  • Outside of for rootRef, 0

  • Outside of for rootRef, 1

  • Inside of rootref, 0

  • Inside of rootref, 1



Actual result:


  • Outside of for rootRef, 0

  • Outside of for rootRef, 1

  • Inside of rootref, 1

  • Inside of rootref, 2



for (var each = 0; each < alumAroundId.length; each++) {
console.log("outside of rootRef", each);
rootRef.child('users').child(alumAroundId[each].key).once('value', function (eventSnap) {
console.log(each, "inside the rootRef is off");
var thisUser = eventSnap.val();
thisUser.distance = alumAroundId[each].distance;
$scope.allAlumAround.push(thisUser);
});
}

Answer

You should read up on closures and how to use them. The main issue is that the for loops contents do not create a new scope on each iteration. So by the time your for loop finishes your "each" variable has been changed to the last one. When the firebase query is done it uses this value. You can get around this by doing the following closure:

 for (var each = 0; each < alumAroundId.length; each++) {
    console.log("outside of rootRef", each);
    (function(each){    
        rootRef.child('users').child(alumAroundId[each].key).once('value', function (eventSnap) {
            console.log(each, "inside the rootRef is off");
            var thisUser = eventSnap.val();
            thisUser.distance = alumAroundId[each].distance;
            $scope.allAlumAround.push(thisUser);
        });
    })(each);
 }