Firebase:如何在所有初始 "child_added" 调用后 运行 回调?

Firebase: How to run a callback after all the initial "child_added" calls?

当监听 "child_added" 事件时:

ref.on("child_added", function (snapshot) {

});

此回调函数最初将为引用中存在的每个子项 运行 一次。

This event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added.

https://firebase.google.com/docs/reference/node/firebase.database.Reference

我想利用这个事实和排序函数来构造一个有序数组:

orderedArray = [];

ref.orderByValue("rating").on("child_added", function (snapshot) {
    orderedArray.push(snapshot.val())
});

// how do I run a callback after the last child has been added?

但是,(据我所知)没有办法告诉 child_added 回调最后一次被调用,因此我不能准确地 运行 我自己的回调在最后一次调用之后child 已添加到我的数组中。


这是我现在的解决方法:

orderedArray = [];

ref.orderByValue("rating").on("child_added", function (snapshot) {
    orderedArray.push(snapshot.val())
});

setTimeout(function() {

    ref.off("child_added") // unbind event
    callback()

}, 3000)

这很粗略,尤其是在从数据库中获取所有数据需要超过 3 秒的情况下。

有什么想法吗?

您可以迭代父快照并使用 DataSnapshot.forEach:

将子快照排序到数组中
const ref = firebase.database().ref().child('items');
const items = [];
ref.once('value', snap => {
  snap.forEach(item => { items.push(item) });
  console.log(items);
});

由于您调用 ref.off() 来读取一次数据,因此使用 .once() 方法并迭代父快照是有意义的。

我尝试做的是使用 observeSingleEvent 侦听器。

// Following a Swift code but the logic remains same.
Database.database()
.reference(withPath: "The_Path")
.observeSingleEvent(of: .value) { (snapshot) in
    // Iterate and save the values from the snapshot.
    // Now initiate `childAdded` and `childChanged` listeners.
    self.keepObserving()
}

并在完成时添加 childAddedchildChanged

func keepObserving() {
    Database.database()
    .reference(withPath: "The_Path")
    .observe(.childAdded) { (snapshot) in
        // Check if the value in the snapshot exists in the your array or data model.
        // If not then add it to your container else return.
    }

    Database.database()
    .reference(withPath: "The_Path")
    .observe(.childChanged) { (snapshot) in
        // Find the indexOf the data in snapshot in array or container.
        // If the index is found or exist replace the changed value.
    }
}