javascript - Firebase JS API : How to avoid `off()` getting executed before `on()` is called/finished executing?

标签 javascript firebase firebase-realtime-database

在下面的代码中,off()on() 之前执行。发生这种情况是因为

The DataSnapshot passed to the callback will be for the location at which on() was called. It won't trigger until the entire contents has been synchronized.

如文档中所述:https://firebase.google.com/docs/reference/js/firebase.database.Reference#on

quotesRef.orderByChild('index').on('value', function(snapshot) {
    snapshot.forEach(function(childSnapShot) {
        vm.allQuotes.push({
            key: childSnapShot.key,
            quoteTxt: childSnapShot.val().quote
        })
    })
})

quotesRef.off('value')

如何构造上述代码,以便仅在内容完全同步或实际调用 on 时调用 off()

谢谢

最佳答案

要在从数据库读取数据后调用 off,请将其移至回调中:

quotesRef.orderByChild('index').on('value', function(snapshot) {
    snapshot.forEach(function(childSnapShot) {
        vm.allQuotes.push({
            key: childSnapShot.key,
            quoteTxt: childSnapShot.val().quote
        })
    })
    quotesRef.off('value')
})

但正如 André 评论的那样,这与使用 once() 完全相同:

quotesRef.orderByChild('index').once('value', function(snapshot) {
    snapshot.forEach(function(childSnapShot) {
        vm.allQuotes.push({
            key: childSnapShot.key,
            quoteTxt: childSnapShot.val().quote
        })
    })
})

关于javascript - Firebase JS API : How to avoid `off()` getting executed before `on()` is called/finished executing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55323284/

相关文章:

javascript - "Assertion failed: you need to wait for the runtime to be ready"在JavaScript中调用C函数时出错

android - Firebase Firestore - 移动 SDK 和 Web SDK 之间的差异

ios - 将自定义类转换为 NSDictionary

java - Android Firebase 更新现有值而不是 setValue 创建新记录

swift - 无法将模块 'fireBaseDatabase' 加载为 'FirebaseDatabase'

ios - Firestore 文档创建失败,但没有错误

javascript - 如何在 React 中定义 setFieldValue

javascript - 干净利落!当用户点击 link_to image_tag 时模型的属性

firebase - 基于 map 值的 Firestore 安全规则

javascript - 如何在tensorflow.js中使用自定义模型对图像进行分类?