0

I have a list of alumIds 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);
    });
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Xiaofan Wu
  • 109
  • 1
  • 13

1 Answers1

2

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);
 }
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90