【问题标题】:javascript Firebase how to fire 'value' events in sequence?javascript Firebase如何按顺序触发“值”事件?
【发布时间】:2017-11-08 04:16:03
【问题描述】:

我有一个触发两个“价值”Firebase 事件的函数。一个是需要得到children的个数,对应下一个的最深路径。

function myFunction(data){
//get last child 
var lastchild = 0;
var data_child = firebase.database().ref('rooms/' + 633 + '/' + 630);
data_child.once('value', function(child) {
    if(child.exists()){
        lastchild = child.numChildren();
        console.log('function 1');
    }else{
        console.log('error no child');
    }
});
//use this number to read the path
var msgsStored = firebase.database().ref('rooms/' + 633 + '/' + 630 + '/' + lastchild);
    msgsStored.orderByChild('datetime').once('value', function(snapshot) {
        var store = (snapshot.val());
        snapshot.forEach(function(child) {
        console.log('function 2');
        //do something
        }
    }
}//myFunction

Firebase 始终会在第一个事件之前触发最后一个“值”事件。为什么? 这将始终导致变量 lastchild = 0;并且“功能 2”将始终在控制台上的“功能 1”之前打印。 我也尝试创建一个回调();函数尝试使用 JavaScript 控制顺序,但不起作用。 我知道 Firebase 的不同事件以不同的顺序触发,但就我而言,我只需要读取存储的数据。 有人知道我缺少什么以及如何解决我的问题吗?

【问题讨论】:

    标签: javascript firebase


    【解决方案1】:

    Firebase 与大多数现代网络一样,从其数据库中异步读取数据。通过在代码中放置一些日志语句,最容易看到这一点:

    console.log("1");
    var data_child = firebase.database().ref('rooms/' + 633 + '/' + 630);
    data_child.once('value', function(child) {
      console.log("2");
    });
    console.log("3");
    

    这个的输出是:

    1

    3

    2

    这可能不是您最初的预期,但可以解释您所看到的行为。当日志语句 3 执行时,来自第一个侦听器的数据尚未加载。因此,您无法根据该数据进行查询。

    因此,您始终需要将需要数据的代码移入回调:

    var lastchild = 0;
    var data_child = firebase.database().ref('rooms/' + 633 + '/' + 630);
    data_child.once('value', function(child) {
        if(child.exists()){
            lastchild = child.numChildren();
    
            //use this number to read the path
            var msgsStored = firebase.database().ref('rooms/' + 633 + '/' + 630 + '/' + lastchild);
        
            msgsStored.orderByChild('datetime').once('value', function(snapshot) {
                var store = (snapshot.val());
                snapshot.forEach(function(child) {
                    console.log('function 2');
                    //do something
                }
            }
        }else{
            console.log('error no child');
        }
    });
    

    【讨论】:

    • 你的回答很有道理,我只是想不通。谢谢你的解释,让我敞开心扉。
    • 不客气,阿德里。这是您开始使用 Web API 时的主要障碍之一,因此我很乐意帮助您克服它。
    猜你喜欢
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2017-11-06
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    相关资源
    最近更新 更多