【问题标题】:Fetching and displaying data from Firebase takes time从 Firebase 获取和显示数据需要时间
【发布时间】:2017-04-08 17:38:28
【问题描述】:

我正在从 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的值需要几秒钟。

有什么问题?为什么加载数据库值需要这么长时间?还是设置值有问题?

【问题讨论】:

  • 在.once 之前定义var pid;,对吗? pid1 也一样。另外,[i] 是什么?我没有看到 i 声明,即,您没有使用 for 循环,而是在执行 forEach。最后,您是否嵌套了.once 方法?可以使用promise.all 或者不嵌套它们,或者链接.thens?

标签: javascript firebase firebase-realtime-database


【解决方案1】:

对 firebase 的请求是异步,因此“显示标记” 代码将在“获取 pid” 代码完成之前运行。 p>

您可以添加另一个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();
    });

  })

【讨论】:

  • 也可以将显示标记代码包装在一个函数中,然后在第一个末尾调用该函数
猜你喜欢
  • 2020-03-06
  • 1970-01-01
  • 2020-05-02
  • 2021-10-01
  • 2016-03-29
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
相关资源
最近更新 更多