Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use for in loop and query data from firebase

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.

like image 964
M. Holm Avatar asked Jan 26 '26 02:01

M. Holm


1 Answers

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);
}
like image 135
Renaud Tarnec Avatar answered Jan 28 '26 15:01

Renaud Tarnec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!