首页 > 解决方案 > Firebase once() 多次触发

问题描述

我正在尝试在烧瓶应用程序中使用 js 从 firebase 检索数据。虽然它有点工作,但它执行的次数比一次多得多。这是我的代码。我只是想获取消息 ID,将它们保存在数组中,然后在打开聊天框时添加它们。我只希望它执行一次。我能做些什么?

这是我的代码:

//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);
                    }
                }
        });
}   

所以,它的第一次迭代,执行 5 次,只收到 5 条消息:

但是,我得到了这个(不断地不断,永不停息,页面崩溃):

在此处输入图像描述

我究竟做错了什么?

提前致谢 :)

标签: javascriptfirebaseflaskfirebase-realtime-database

解决方案


once()在一个for循环中调用。因此,当然,您可以期望它每次在循环中被调用时执行,长度为mensajes.


推荐阅读