Tyler.G
Tyler.G

Reputation: 143

wait for for loop to finish before executing next function

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

Upvotes: 2

Views: 598

Answers (2)

KKK
KKK

Reputation: 61

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

I prefer that to prevent allocating memory.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

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)

Upvotes: 2

Related Questions