简体   繁体   English

Firebase once() 多次触发

[英]Firebase once() triggered more than once

I'm trying to retrieve data from firebase with js in a flask app.我正在尝试使用 Flask 应用程序中的 js 从 firebase 检索数据。 Although it kinda works, it's executed a lot more times than once.虽然它有点工作,但它执行的次数远不止一次。 This is my code.这是我的代码。 I'm just trying to get the messages id's, save them on an array and then adding them when the chatbox is opened.我只是想获取消息 ID,将它们保存在一个数组中,然后在打开聊天框时添加它们。 I just want it to execute once.我只希望它执行一次。 what can I do?我能做什么?

This is my code:这是我的代码:

//Getting the messages id of the logged in user from firebase and pushing them into the array
firebase.database().ref().child("user-messages").child("{{usuario}}").once('value', function(snapshot) {
        console.log(snapshot.val());
        snapshot.forEach(function(child) {
           console.log("Child:  " + child.key + "//////" + child.val());
           var msg = {};
           msg.key = child.key;
           msg.val = child.val();
           mensajes.push(msg);
        });

});

//Looping the array and looking for the messages on firebase
for(i = 0; i < mensajes.length; i++){
        console.log(mensajes);
        firebase.database().ref().child("Mensajes").child(mensajes[i].key).once('value', function(childsnapshot) {
                var id;
                if(mensajes[i].val == "1"){
                    id = usuario[0].nombre.split(" ")[0];
                    user = buscarUsuario(childsnapshot.val().to);
                } else if(mensajes[i].val == "2"){
                    user = buscarUsuario(childsnapshot.val().from);
                    id = user.nombre.split(" ")[0];
                }

                if (user.user == usuarios[index].user){
                    if(chat.length){
                        chat.chatbox("option", "boxManager").addMsg(id, childsnapshot.val().message);
                    } else{
                        div.chatbox("option", "boxManager").addMsg(id, childsnapshot.val().message);
                    }
                }
        });
}   

So, the first iteration it works, executes 5 times, only got 5 messages:所以,它的第一次迭代,执行了 5 次,只得到了 5 条消息:

But then, I get this (goes on and on and on, never stops, page crashes):但是后来,我明白了(一直继续,永不停息,页面崩溃):

在此处输入图片说明

What am I doing wrong?我究竟做错了什么?

Thanks in advance :)提前致谢 :)

You're calling once() inside a for loop.您在for循环中调用once() So, of course, you can expect it to execute for each time it's called in the loop, the length of mensajes .因此,当然,您可以期望它每次在循环中被调用时都会执行,即mensajes的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM