2017-04-08 85 views
0

我正在從Firebase數據庫讀取pid的值,然後使用此pid值,我從數據庫中獲取更多值。從Firebase獲取和顯示數據需要時間

//fetching pid 
firebaseRef.once("value") 
    .then(function(snapshot) { 
    snapshot.forEach(function(childSnapshot) { 
     //getting key of the child 
     var pid = childSnapshot.key; 
     // childData will be the actual contents of the child 
     var childData = childSnapshot.val(); 
     pid[i].id = "pid" + (i + 1); 
     document.getElementById(pids[i].id).innerText = pid; 
     i++; 
    }); 
    }); 

//displaying marks 
var pid1 = document.getElementById("pid1").innerHTML; 
guideRef = firebase.database().ref("internal").child(pid1).child("guide"); 
guideRef.child("report").once('value').then(function(snapshot) { 
    document.getElementById(reportGuideMarks).value = snapshot.val(); 
}); 

但捉迷藏這個代碼,我得到這個錯誤:

Uncaught Error: Firebase.child failed: First argument was an invalid path: "". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"

PID誤差是由於PID1被空。但是當我在「顯示標記」部分放置3秒鐘時,代碼運行完美。

甚至在設置了pid的值之前執行顯示標記。

需要幾秒鐘來設置表中的pid值。

問題是什麼?爲什麼需要很長時間來加載數據庫的值?或者這是設置值的問題?

+0

定義'變種PID;'之前外'.once',對不對? 'pid1'一樣。另外,'[我]'是什麼?我沒有看到'我'的聲明,即你沒有使用for循環,而是使用for each。最後,你是否嵌套'.once'方法?可能使用'promise.all'或者不要嵌套這些,或者鏈接'.thens'? –

回答

1

請求火力是異步所以「讀取PID」代碼完成之前的「顯示標記」代碼將運行。

你可以添加其他then()所以第二部分將不會運行,直到第一部分已經完成

//fetching pid 
firebaseRef.once("value") 
    .then(function(snapshot) { 
    snapshot.forEach(function(childSnapshot) { 
     //getting key of the child 
     var pid = childSnapshot.key; 
     // childData will be the actual contents of the child 
     var childData = childSnapshot.val(); 
     pid[i].id = "pid" + (i + 1); 
     document.getElementById(pids[i].id).innerText = pid; 
     i++; 
    }); 
    }) 
    // new then() won't fire until prior then() is completed 
    .then(function() {  
    //displaying marks 
    var pid1 = document.getElementById("pid1").innerHTML; 
    guideRef = firebase.database().ref("internal").child(pid1).child("guide"); 
    guideRef.child("report").once('value').then(function(snapshot) { 
     document.getElementById(reportGuideMarks).value = snapshot.val(); 
    }); 

    }) 
+1

也可以在函數中包裝顯示標記代碼,並在第一次結束時調用該函數,然後改爲 – charlietfl

相關問題