Reputation: 2161
I am trying to rank a list of user based on how many times they appear in several list:
function getRegistrationsFromSportList(sportList){
console.info('[DatabaseService-getRegistrationsFromSportList] Getting registrations to sports...');
var promiseHash = {};
sportList.forEach(function (sport){
promiseHash[sport] = firebase.database().ref('/sport_registrations/' + sport).once('value');
});
return $q.all(promiseHash);
}
getUserSportListPromise(user.uid).then(function(sportList){
return getRegistrationsFromSportList(sportList);
})
.then(function(registrationsHash){
console.info('[DatabaseService-getMatches] Processing matches...');
var matches = [];
angular.forEach(registrationsHash, function(regsSnap, sport){
console.dir(regsSnap.val());
regsSnap.forEach(function(user){
if (matches.indexOf(user.key) > -1) {
matches[user.key]++;
} else{
matches[user.key] = 1;
}
console.dir(matches);
});
});
});
}
Here is my console log:
Object
e8wXuTklnVcYknc0MYn34xlcqmA3: true
Array[0]
Lvwr4lkZ58SnhrZzft6FhT08iVN2: 1
ND9iZYJ3gfQUvjKSRaKKc8NEkAj2: 1
SA0h1iHwyCSeytgh6FOglSf1sOs2: 1
e8wXuTklnVcYknc0MYn34xlcqmA3: 1
Object
Lvwr4lkZ58SnhrZzft6FhT08iVN2: true
ND9iZYJ3gfQUvjKSRaKKc8NEkAj2: true
SA0h1iHwyCSeytgh6FOglSf1sOs2: true
e8wXuTklnVcYknc0MYn34xlcqmA3: true
Array[0]
Lvwr4lkZ58SnhrZzft6FhT08iVN2: 1
ND9iZYJ3gfQUvjKSRaKKc8NEkAj2: 1
SA0h1iHwyCSeytgh6FOglSf1sOs2: 1
e8wXuTklnVcYknc0MYn34xlcqmA3: 1
Any suggestion? Help?
Thanks!
Upvotes: 2
Views: 2888
Reputation: 1162
No, forEach() is not async, both the angular or native one.
For the first question, I don't think there's enough code to see why your code behaves that way, what is returned by the others? can you paste the full console output?.
For your second question, this comparison is always false, matches.indexOf(user.key) > -1
, is better if you use if (matches[user.key] )
or even a tertiary expression like:
matches[user.key] = matches[user.key] ? matches[user.key] + 1 : 0;
For the third question, because you haven't pushed any element to the array, you're adding values to keys, but technically the array has zero elements until you use numeric keys or use the push method. Either change matches to be an object, or change the way you store and retrieve information from it.
Upvotes: 5