0

I wrote a code that querying Firebase:

db.collection("products").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        var arr = [];
        let id = {id: doc.id};
        arr = doc.data();
        Object.assign(arr, id);
        productsArray.push(arr);
    });
    // Should I put the rest of the code here?
});
// Rest of the code is here now
var idFromButton = JSON.parse(sessionStorage['productID'].toString());

  let product = productsArray.find((el) => el.id === idFromButton);
  numberOfImages = product.numberOfImages;

Any code I wrote outside of this throws me an error: "Uncaught TypeError: Cannot read property 'id' of undefined", etc. I assume because they run faster than the database query. Should I really put those where I mark? That way it works, but this is the proper way? What if I have to query again?

Basically, I'd like the rest of the code run only when the querying has finished.

Thank you!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

0 Answers0