简体   繁体   中英

How do I fetch the total number of child nodes from my firebase realtime database in javascript?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM