Vanilla JS, trying access objects in an array

Viewed 88

I can't access the contents of an array I saved from a firestore snapshot.

Here is the code:

function getDataFromFirestore() {
  let myList = [];
  db.collection("test")
    .get()
    .then((snapshot) => {
      snapshot.forEach((doc) => {
        myList.push(doc.data());
      });
    });

  console.log(myList);
  console.log(myList[1]);
  console.log(myList.length);
}

getDataFromFirestore();

here is return of console.log():

result of console.log()

Questions: Why were 3 items saved in the array using forEach and the length of it is = 0?

How do I access the objects saved in the array?

Thank you very much for your help.

1 Answers

db.collection("test").get() returns a promise, which means that is executed after the console.logs at the end.

A solution could be to move the console.logs inside then, or to use async await.

Related