wait for the loop to finish before executing the next function

What you’re seeing is expected, as the get() calls to Firestore are asynchronous.

You can’t really wait for them. But with await (or even Promise.all()) you can get pretty close:

let promises = [];
for (i = 0; i < this.state.gameRoomMembers.length; i++) {
  promises.push(firebase.firestore().collection('users').doc(this.state.gameRoomMembers[i]).collection('groupChats').get());
}
let experimentArray = []
Promise.all(promises).then(snapshots => {
  snapshot.forEach(snapshot => {
     if (!snapshot.empty) {
       snapshot.forEach(doc => {
         experimentArray.push(doc.data().key)
       })
     }
  })
});
console.log(experimentArray.length)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top