使用 Firebase.on('child_added') 的无限循环

Infinite loop with Firebase.on('child_added')

本文关键字:added 无限循环 child on Firebase 使用      更新时间:2023-09-26

我有一个聊天应用程序,其中消息存储在Firebase集合中。

有一个浏览器客户端侦child_added听收集:

const chatRef = new Firebase()
chatRef.on('child_added', function(snapshot) { //... })

我还有一个服务器客户端,它侦听同一集合上的相同事件。当服务器客户端看到消息已添加到集合中时,将触发回调以处理该消息,并将新消息推送到集合中:

const chatRef = new Firebase()
chatRef.on('child_added', function(snapshot) {
  const outgoingMessage = processIncomingMessage(snapshot.val())
  chatRef.push(outgoingMessage)
})

这会导致无限循环,因为服务器现在将尝试处理已添加到 Firebase 集合中的消息。

有没有办法避免这种情况?我想我需要在Firebase中重组我的数据,但我不太确定这应该是什么样子。

有很多方法可以删除它。但这实际上取决于您希望它如何工作。

一种方法是使服务器可以忽略它自己发送的消息。

为此,您需要一个列表来保存您要发送的任何项目的推送 ID:

var pendingKeys = [];

然后,当您发送消息时,将其推送 ID 添加到此列表中:

var newRef = chatRef.push();
pendingKeys.push(newRef.key);
newRef.set(outgoingMessage);

现在,当您收到一个child_added 时,当该消息位于待处理键列表中时,您将忽略该消息。

chatRef.on('child_added', function(snapshot) {
  var index = pendingKeys.indexOf(snapshot.key());
  if (index >= 0) {
    const outgoingMessage = processIncomingMessage(snapshot.val())
    chatRef.push(outgoingMessage)
  }
  else {
    pendingKeys.splice(index,1);
  }
})

您会注意到,此时我还使用splice()从列表中删除键,否则列表将无限期地增长。