I have a query that gets all keys of users in my firebase database. Those keys er saved into an array. I would then like to loop through the array and inside the loop query for the users name. The problem is that it stops when the first name is loaded - the loop does not query through even though there are 1000 keys inside the array?
var i;
for (i = 0; i < emailArray.length; i++) {
userIDgotten = emailArray[i];
console.log(userIDgotten);
return firebase.database().ref('/users/' + userIDgotten).once('value').then(function(snapshotUser) {
const name = snapshotUser.val().name;
console.log("NAME: " + name);
allTicketEmailsFromUsers = allTicketEmailsFromUsers + ", " + name;
console.log(allTicketEmailsFromUsers);
});
}
I get no errors but the loop just stops after the first name is retrieved.
The once() method is asynchronous and returns a Promise.
Since you want to execute several queries with once() in parallel, you need to use Promise.all() as follows:
var promises = [];
for (var i = 0; i < emailArray.length; i++) {
userIDgotten = emailArray[i];
console.log(userIDgotten);
promises.push(firebase.database().ref('/users/' + userIDgotten).once('value'));
}
Promise.all(promises)
.then(function(results) {
var allTicketEmailsFromUsers = "";
results.forEach(function(snapshotUser) {
const name = snapshotUser.val().name;
console.log("NAME: " + name);
allTicketEmailsFromUsers = allTicketEmailsFromUsers + ", " + name;
});
console.log(allTicketEmailsFromUsers);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With