从Firebase获取和显示数据需要时间
问题描述:
我正在从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值。
问题是什么?为什么需要很长时间来加载数据库的值?或者这是设置值的问题?
答
请求火力是异步所以“读取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
定义'变种PID;'之前外'.once',对不对? 'pid1'一样。另外,'[我]'是什么?我没有看到'我'的声明,即你没有使用for循环,而是使用for each。最后,你是否嵌套'.once'方法?可能使用'promise.all'或者不要嵌套这些,或者链接'.thens'? –