简体   繁体   中英

Fetching and displaying data from Firebase takes time

I'm reading value of pid from Firebase database and then using this pid value, I'm fetching further values from the database.

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

But runnning this code I get this error:

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

The pid error is due to pid1 being null. But when I put delay of 3 seconds on the 'displaying marks' part, the code runs perfectly.

The displaying marks executes even before the values of pid have been set.

It takes a few seconds to set the value of pid in the table.

What is the issue? Why does it take so much time to load values of database? Or is it an issue with setting the value?

Requests to firebase are asynchronous so the "displaying marks" code will run before the "fetching pid" code has completed.

You could add another then() so the second part won't run until the first part has completed

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

  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM