gpt4 book ai didi

javascript - 如何使用Firebase云函数停止读取child_added?

转载 作者:行者123 更新时间:2023-12-01 02:55:29 24 4
gpt4 key购买 nike

我尝试使用以下方法获取所有 10 条记录:

exports.checkchanges = functions.database.ref('school/{class}').onCreate(snap => {

const class=snap.params.class;

var ref = admin.database().ref('/students')
return ref.orderByChild(class).startAt('-').on("child_added", function(snapshot) {

const age=snapshot.child("age");
// do the thing

})
)}

问题是,在我正确获得所需的 10 条记录后,即使几天后添加满足这些条件的新记录,仍然会调用此函数。

当我将 on("child_added"更改为 once("child_added) 时,我只得到 1 条记录,而不是 10 条。当我更改 on("child_addedon("value 我得到 null :

const age=snapshot.child("age");

那么如何防止将来更改时调用该函数?

最佳答案

在 Cloud Functions 中实现数据库交互时,确定性的结束条件非常重要。否则,Cloud Functions 环境不知道您的代码何时完成,它可能会过早终止代码,或者使其运行时间(从而向您收取费用)超过必要的时间。

您的代码的问题是您使用 on 附加了一个监听器,然后从未将其删除。此外(因为 on() 不返回 promise ),Cloud Functions 不知道您已完成。结果是您的 on() 监听器可能无限期地存在。

这就是为什么在大多数使用实时数据库的云函数中,您会看到它们使用once()。为了让所有子级都具有 once(),我们将监听 value 事件:

exports.checkchanges = functions.database.ref('school/{class}').onCreate(snap => {

const class=snap.params.class;

var ref = admin.database().ref('/students')
return ref.orderByChild(class).startAt('-').limitToFirst(10).once("value", function(snapshot) {
snapshot.forEach(function(child) {
const age=child.child("age");
// do the thing
});
})
)}

我添加了 limitToFirst(10),因为您表示只需要 10 个子级。

关于javascript - 如何使用Firebase云函数停止读取child_added?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46730313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com