Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
Firestore nested forEach queries outer loop finishes first

I am trying to get data from a subcollection from Firestore. I don't even know if that is legal but I created a nested query because I want to put the data I retrieve into "list" array that's why I tried nesting them. The problem I'm having is that the outer loop finishes first then the inner starts. That prevents me from putting the data into "list array". How can I solve this?

  const fetchPosts = async () => {
    try {
      const list = [];

      
      const profileRef = firestore
        .collection("users")
        .doc(auth.currentUser.uid);
      const doc = await profileRef.get();
      setDoc(doc);

      await firestore
        .collection("posts")
        .orderBy("postTime", "desc")
        .get()
        .then((querySnapshot) => {
          //console.log("Total Posts: ", querySnapshot.size);
          querySnapshot.forEach((doc) => {
            const pId = doc.id;
            const path = [];

            firestore
            .collection("posts")
            .doc(pId)
            .collection("route")
            .get().then((querySnapshot)=>{

              querySnapshot.forEach((document) => {
                const array  = document.data();
                const route = Object.values(array)
                console.log("route",route)
                path.push(route)
              })
            })
            console.log("path",path)
            
            const {
              userId,
              userName,
              userSurname,
              post,
              postImg,
              postTime,
              userImg,
              like,
              comment,
              likeByUsers,
            } = doc.data();
            list.push({
              id: pId,
              userId,
              userName,
              userSurname,
              userImg: userImg,
              post,
              postImg,
              postTime: postTime,
              liked: false,
              like,
              comment,
              likeByUsers,
            });
          });
        });

      setPosts(list);

      if (loading) {
        setLoading(false);
      }
      //console.log("Posts: ", posts);
    } catch (e) {
      console.log(e);
    }
  };
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!