I am developing a web application and maintaining the data in Firebase in the following way.
There can be several nodes under the "Users" node and in each of those nodes, I am storing users information such as name, gender etc.
Now I am trying to retrieve names of all users using the following Javascript function.
function getList(){
var nameList = new Array();
var uidList = new Array();
var query = firebase.database().ref('Users');
query.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var name = childSnapshot.val().Name;
var uid = childSnapshot.key;
alert(name); //first alert
nameList.push(name);
uidList.push(uid);
});
});
var len = nameList.length;
alert(len); //second alert
}
When I run this on my browser, at first it shows the length of the array is 0 (in the second alert) and then it shows the name which is being retrieved from the database (in the first alert).
Why is the second alert executing before the first alert? What is the appropriate way to retrieve data from Firebase, so that I can detect that data is retrieved and then execute further code to get the length of namelist
array?
I have tried using a while loop while "name" and "uid" are null, but that didn't work.