Firebase高度异步
这意味着,如果代码依赖于某个执行顺序,则需要确保它按该顺序执行。
这个
once
函数返回
Promise
(更多关于承诺的信息
here
). 你可以注册
scheduleFreeBed
在
Promise.then()
回调函数,所以
onUpdate
在初始化完成后注册。
例如:
// Initialise the bed timeout holder object
beds.once("value", function (snapshot) {
// your existing code...
}).then(() => {
// Frees a bed after a set amount of time
exports.scheduleFreeBed = functions.database.ref('/beds/{hotelIndex}/{bedIndex}/email').onUpdate( (snapshot, context) => {
// your existing code...
});
})
这将确保
计划自由床
只能在初始化完成后触发。
这也意味着
更新
如果在初始化过程中更改了数据,将被忽略!
由于上面的代码显然不起作用,因为异步导出注册显然是一个可怕的想法,下面的代码片段应该是另一种选择,除了确保它在正确初始化之后才执行之外,它还有一个额外的好处,那就是确保调度将按FIFO顺序进行。此外,通过此更改还可以避免初始化期间触发被忽略的先前缺点:
// Initialize the bed timeout holder object
var initPromise = beds.once("value", function (snapshot) {
// your existing code...
});
// Frees a bed after a set amount of time
exports.scheduleFreeBed = functions.database.ref('/beds/{hotelIndex}/{bedIndex}/email').onUpdate( (snapshot, context) =>
// make sure the scheduling happens after the initialization and in order
// since his chaining doubles as a queue
initPromise = initPromise.then(() => {
// your existing code...
})
);