繁体   English   中英

在执行下一个函数之前等待循环完成

[英]wait for for loop to finish before executing next function

我需要等待 for 循环完成,然后才能开始使用“experimentArray”。 在我继续使用experimentArray之前,我如何等到这完成? 我试过承诺、异步等待等

 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

您所看到的是预期的,因为对 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM