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
2
  • on is asynchronous and its callback won't fire until after the last console.log call in your snippet. Commented Jan 9, 2017 at 13:33
  • Possible duplicate of Handling Asynchronous Calls (Firebase) in functions Commented Jan 9, 2017 at 13:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.