0

So i'm trying to see if any of the user is an admin in any event. For some reason, the array will be filled with the index of the last find. Any idea why this is happening?

for(var x = 0;x<=10;x++){
            console.log(x);
            var current = x; 
            firebase.database().ref('/Event/' + x + "/admins").once('value').then(function(snapshot) {
              console.log(snapshot.val()); 
              if(snapshot.val()==uid){
                console.log("Match found at "+(current)+"!");
                matchingEvents.push(current);
              }
            });    
}

The array ends up looking like this: [10,10,10,10,10]

Chris Martinez
  • 79
  • 1
  • 1
  • 9

1 Answers1

0

The loop is already finished by the time the anonymous function is called and so current = 10. It's a scope issue relating to closures.

A correct way of doing this might be

.then((function(current) {
    return function(snapshot) {
        // Things using current
    }
})(current));
TW80000
  • 1,507
  • 1
  • 11
  • 18
  • How is it though? The function is within the loop – Chris Martinez Jul 12 '16 at 17:15
  • The call to the `.then` method is inside your loop, but it merely passes the anonymous function as an argument in each iteration. The references to `current` inside those anonymous functions all end up pointing to the same variable, which is the last time current is updated at the end of the loop, so it ends up with value 10. – TW80000 Jul 12 '16 at 17:19
  • 1
    Look up closures if you want more information on this :) – TW80000 Jul 12 '16 at 17:20