簡體   English   中英

Firebase once() 多次觸發

[英]Firebase once() triggered more than once

我正在嘗試使用 Flask 應用程序中的 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 條消息:

但是后來,我明白了(一直繼續,永不停息,頁面崩潰):

在此處輸入圖片說明

我究竟做錯了什么?

提前致謝 :)

您在for循環中調用once() 因此,當然,您可以期望它每次在循環中被調用時都會執行,即mensajes的長度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM