Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从Firebase获取和显示数据需要时间_Javascript_Firebase_Firebase Realtime Database - Fatal编程技术网

Javascript 从Firebase获取和显示数据需要时间

Javascript 从Firebase获取和显示数据需要时间,javascript,firebase,firebase-realtime-database,Javascript,Firebase,Firebase Realtime Database,我从Firebase数据库中读取pid值,然后使用这个pid值,从数据库中获取更多的值 //fetching pid firebaseRef.once("value") .then(function(snapshot) { snapshot.forEach(function(childSnapshot) { //getting key of the child var pid = childSnapshot.key; // childData wi

我从Firebase数据库中读取pid值,然后使用这个pid值,从数据库中获取更多的值

//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();
});
但运行此代码时,我会遇到以下错误:

未捕获错误:Firebase.child失败:第一个参数是无效路径:。路径必须是非空字符串,并且不能包含.、$、[、或]

pid错误是由于pid1为空。但当我在“显示标记”部分延迟3秒时,代码运行得非常好

显示标记甚至在设置pid值之前执行

在表中设置pid值需要几秒钟的时间

问题是什么?为什么要花这么多时间来加载数据库的值?还是设置值有问题?

对firebase的请求是异步的,因此显示标记代码将在提取pid代码完成之前运行

然后您可以添加另一个,以便在第一部分完成之前第二部分不会运行

//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();
    });

  })

还可以将显示标记代码包装在函数中,并在函数末尾调用该函数,然后代替定义var pid;一次,对吗?pid1也是如此。还有,什么是[我]?我没有看到我声明的,也就是说,你没有使用for循环,你没有使用forEach。最后,您是否正在嵌套。一次性方法?可能会使用promise.all,或者不嵌套它们,或者将它们链起来。然后呢?