Reputation: 99
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.
Upvotes: 3
Views: 1660
Reputation: 83058
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);
}
Upvotes: 2
Reputation: 74
You are using a return
in your loop, which stops the loop.
If you remove that return, it should work the way you expect it to work.
for (var i = 0; i < emailArray.length; i++) {
userIDgotten = emailArray[i];
console.log(userIDgotten);
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);
});
}
Upvotes: 1