-1

I have one problem. I am trying to get value from one variable but I can't do this. If somebody can help I will appreciate that. This is my code.

function getInfo() {
    var ref = firebase.database().ref("db_storage/");
    var info = 0;

    ref.on("value", function(snapshot) {
        info = snapshot.val().length;
    }, function (error) {
        console.log("Error: " + error.code);
    });

    return info;
}

var info = getInfo();
alert(info);
John
  • 3
  • 2
  • Hi and welcome to StackOverflow. My guess is that your `info` isn't what you expect. Please explain what you're getting, and what you think it should be. See https://stackoverflow.com/help/how-to-ask for hints on phrasing your question. –  Aug 30 '18 at 18:03
  • I am getting zero(0). I need to get number of elements in array(rows in my database). snapshot.val().length return this number, but I can't use this number outside of function. – John Aug 30 '18 at 18:11
  • This is (probably) because your `info = snapshot.val().length` is happening in an *asynchronous* callback. Take a look at https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 and https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron –  Aug 30 '18 at 18:14

1 Answers1

0

Further to my comment above.

The ref.on("value"...) is an event listener that gets triggered when the 'value' event is dispatched by the database ref. When your code runs it goes (roughly speaking) into getInfo(), attaches the event listener, then proceeds to your last line without waiting for the 'value' event.

To hook things up, pass a callback function as follows.

function getInfo(callback) {
    var ref = firebase.database().ref("db_storage/");

    ref.on("value", function(snapshot) {
        var info = snapshot.val().length;
        return callback(info);
    }, function (error) {
        console.log("Error: " + error.code);
        return callback(0);
     });
}

getInfo(function(info) {
    alert(info);
});
  • That's it. Thanks for help and for explanations. It works. – John Aug 30 '18 at 18:30
  • Would you mind accepting this answer then -- thanks. https://stackoverflow.com/help/someone-answers –  Aug 30 '18 at 18:31