简体   繁体   中英

Why is firebase statement inside loop being ignored?

I am coding a project using node.js. This project makes use of firebase realtime database, where data can be sent to and read from. Part of my project involves a loop which will constantly read an area of the database, and will do an action. For demonstration sake, the program should print the contents of the database directory to the console. Here is the code:

while (true){
    console.log("HI");
    firebase.database().ref(key).once("value", function(snapshot){
        var data = snapshot.val();
        console.log(data);
    });
    sleep(2000);
}

It is a basic while loop that constantly checks firebase database and prints its content.There is a sleep function at the end to prevent overloading the server for firebase. The sleep function lasts for 2 seconds. Although it may not be necessary, I've added the code of the sleep function too:

function sleep(milliseconds) {
    const date = Date.now();
    let currentDate = null;
    do {
        currentDate = Date.now();
    } while (currentDate - date < milliseconds);
}

ISSUE = The main issue is that this code currently just prints "HI" to the console every 2 seconds. And even though there is data in the database section, it is not being printed. It is almost as if my firebase function doesn't exist.

WHAT I WANT IT TO DO = An ideal solution would be one that would make it print "HI" and then the contents of the database every 2 seconds.

Thanks

According to: https://firebase.google.com/docs/reference/js/firebase.database.Reference#once once will listen to a change in the document, so unless the document has changed then it will not be invoked.

If you want to read the document consider using get as specified in https://firebase.google.com/docs/reference/js/firebase.database.Reference#get

Additionally, as Joeman said, instead of using a sleep function, consider using an event listener like on https://firebase.google.com/docs/reference/js/firebase.database.Reference#on

why are you using a while loop you know you can just use onSnapshot to listen for realtime changes??? You don't need to print the contents of the db every two seconds just print it once when you start and once per change.

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