Reputation:
I want to fetch the total number of child nodes present in my firebase realtime db
. This is my code:
function return_noofrecords(){
var no_of_fbkeys = 0;
firebase.database().ref("ac_transaction/0/").once('value', function(snapshot){
no_of_fbkeys = snapshot.numChildren();
console.log(no_of_fbkeys); // this prints the correct value
})
console.log(no_of_fbkeys); //keeps printing 0
return no_of_fbkeys;
}
var no_of_rec = return_noofrecords();
console.log(no_of_rec); //always prints 0
When I execute the above code, it keeps printing 0 in my console. Why?
I want the no_of_rec
variable to have the correct value.
Upvotes: 0
Views: 93
Reputation: 21
Use console.log(); inside the firebase call.
Reason: console.log executes before Firebase can respond.
function return_noofrecords(){
var no_of_fbkeys = 0;
firebase.database().ref("ac_transaction/0/").once('value', function(snapshot){
snapshot.forEach(function (child){
no_of_fbkeys = child.key;
})
console.log(no_of_fbkeys); // prints
})
return no_of_fbkeys;
}
var no_of_rec = return_noofrecords();
Upvotes: 1