等待循环完成,然后再执行下一个功能

时间:2020-11-02 23:47:01

标签: javascript firebase google-cloud-firestore

我需要等待for循环完成,然后才能开始使用'experimentArray'。在继续使用experimentArray之前,我该如何等到完成为止?我已经尝试过Promise,异步等待等

 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 个答案:

答案 0 :(得分:2)

您所看到的是预期的,因为对Firestore的get()调用是异步的。

您真的不能等待。但是,使用await(甚至是Promise.all()),您可以非常接近:

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)

答案 1 :(得分:0)