簡體   English   中英

javascript Firebase如何按順序觸發“值”事件?

[英]javascript Firebase how to fire 'value' events in sequence?

我有一個函數觸發兩個“值” Firebase事件。 一個必須獲得孩子的數量,該數量對應於下一個孩子的最深路徑。

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”之前打印。 我也嘗試創建一個callback(); 函數嘗試使用JavaScript控制順序,但無法正常工作。 我知道Firebase的不同事件以不同順序觸發,但就我而言,我只需要讀取存儲的數據。 有人知道我在想什么,如何解決我的問題?

與大多數現代網絡一樣,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

這可能不是您最初期望的,但是可以解釋很多您所看到的行為。 執行log語句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');
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM