0

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. e.g. 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)
}
1
  • you are updating HardProblems asynchronously in success callback of then() that's why you are not getting anything in console. Try adding the log in callback method just after forEach Commented Mar 30, 2020 at 3:22

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What I am saying is that HardProblems is being cleared after the query. I fixed it by not declaring HardProblems in the method (nor even initializing it after declaring it globally). IDK how that fixed it.
Oooh yeah that's just scoping. If you declare something in a function body, it only lasts for the lifetime of that function, not after the function has finished. So yes, declaring HardProblems in the global scope would fix this issue. You could also just return HardProblems from the function (as long as it was inside the .then()), and then access it from outside.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.