3

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.

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.