0

I have this structure in my database tree two nodes that contain the information of the messages of my web, in the node 'Messages' I have stored the information of all the messages and in the node 'User-messages' I have created a reference to These messages, for example, when a user sends a message, the key of that message is stored in this node (User-messages), and thus creates a list of the keys of all the messages that that user has sent, which Will serve to locate which messages belong to that particular user in the list of all sent messages

tree example

   var  RefMessage=new Firebase('https://chatfbexample.firebaseio.com/user-messages/332');
   var oMessages=[];
   var All= new Firebase('https://chatfbexample.firebaseio.com/all-messages');
   RefMessage.on("value",function(snapshot){

            snapshot.forEach(function(snap){
                var key=snap.key();
                var mensajeR=All.child(key);
              mensajeR.on('value',function(snap){
                var id=snap.val().id;
                oMessages[id]=[];
                oMessages[id]['id']=id;
               });

            });

        for(i in oMessages)
        {
            console.log(oMessages[i]['id']);
        }
        });

I store the data in arrays since I only want to get the last value (message) that has been stored,However, when I try to display the data with the loop it does not return anything to me, If I check the array, I see that the values have been stored, in fact, doing a console log without using the 'for' shows me the array, my question is, how can I display this data after retrieving it??

1 Answer 1

1

That's because firebase calls are run asynchronously and when your for loop executes it's not finished doing the calls. Look into promises and then chaining off when your .on's finish.

If you change your code to this:

var RefMessage = new Firebase('https://chatfbexample.firebaseio.com/user-messages/332');
var oMessages = [];
var All = new Firebase('https://chatfbexample.firebaseio.com/all-messages');
RefMessage.on("value", function (snapshot) {

    snapshot.forEach(function (snap) {
        var key = snap.key();
        var mensajeR = All.child(key);
        mensajeR.on('value', function (snap) {
            console.log('done call');
            var id = snap.val().id;
            oMessages[id] = [];
            oMessages[id]['id'] = id;
        });

    });
    console.log('trying loop');

    for (i in oMessages) {
        console.log(oMessages[i]['id']);
    }
});

You'll see the 'trying loop' console log before the 'done call' one(s).

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.