wait for for loop to finish before executing next function

Viewed 194

I need to wait for my for loop to be completed before i can start using the 'experimentArray'. How do i wait until this is complete before i move onto using the experimentArray? i've tried promises, async await, etc

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

2 Answers

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)
Related