简体   繁体   中英

problem with array not saving values after firebase query

The variable HardProblems is not being updated after the function completes. It is being updated within the loop but does not save. This is a firebase call. eg HardProblems.length is 0 but should be nonzero.

function getHardProblems(){
  var HardProblems = [];
  var foo = [];
  db.collection("hardproblems")
  .get()
  .then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          // doc.data() is never undefined for query doc snapshots
          //console.log(doc.id, " => ", doc.data());
          HardProblems.push({docID: doc.id, ...doc.data()});
      });
  })
  .catch(function(error) {
      console.log("Error getting documents: ", error);
  });

  console.log("Got Hard Problems "+HardProblems.length)
}

You are logging HardProblems outside of the async code, move it into the then() block:

function getHardProblems(){
  var HardProblems = [];
  var foo = [];
  db.collection("hardproblems")
  .get()
  .then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          // doc.data() is never undefined for query doc snapshots
          //console.log(doc.id, " => ", doc.data());
          HardProblems.push({docID: doc.id, ...doc.data()});
      });
    console.log("Got Hard Problems " + HardProblems.length) // have to have this in the 'then()' block
  })
  .catch(function(error) {
      console.log("Error getting documents: ", error);
  });
}

JavaScript will run the async code AFTER all of the stuff in the main area gets run. So, when you were logging HardProblems , even though it was after the async code in the program source, it gets executed BEFORE the async code is run, so that's why you were seeing an empty array, because it still WAS empty.

Flavio has a good explanation of how async code and the event loop works here .

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