0

I have tried to save snapshot properties in arrays, but for some reason, when I store the data inside the query, for example with on or child_added and run the data with a foreach, the data is displayed inside the Loop and the query, but out of this its value is undefined, I tried with objects but only rescued the last value, How could this problem be solved?

Here's a code snippet:

var array=[];
var ref= firebase.database().ref().child('messages');
ref.orderByChild("fecha").on('value',function(snapshot){
    snapshot.forEach(function(snap){
        //test array
        array[0] = snap.val().text;
        console.log(array[0]);//show the data
    });
});

//but out of the loop
console.log(array[0]);//Return undefined
AL.
  • 36,815
  • 10
  • 142
  • 281
Felipe Castillo
  • 536
  • 8
  • 25
  • `on` is asynchronous and its callback won't fire until after the last `console.log` call in your snippet. – cartant Jan 09 '17 at 13:33
  • Possible duplicate of [Handling Asynchronous Calls (Firebase) in functions](http://stackoverflow.com/questions/11636731/handling-asynchronous-calls-firebase-in-functions) – cartant Jan 09 '17 at 13:33

1 Answers1

4

The console.log at the bottom runs before the one in the loop. This is called asynchronous code.

You cannot access the values before they have been returned from the API. The .on function waits for the data to be ready and then runs, which is why the data is then available.

There is no way to "save" the data outside of the callback - the only place that you know what it is will be inside the callback. You can of course pass it to another function from inside the callback, but there's no way to extract it to the position of your second console.log.

clinton3141
  • 4,751
  • 3
  • 33
  • 46