等待循环完成,然后再执行下一个功能 [英] wait for for loop to finish before executing next function
本文介绍了等待循环完成,然后再执行下一个功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要等待for循环完成,然后才能开始使用'experimentArray'.在继续使用experimentArray之前,我该如何等到完成为止?我已经尝试过Promise,异步等待等
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
推荐答案
所见即所得,因为对Firestore的 get()
调用是异步的.
What you're seeing is expected, as the get()
calls to Firestore are asynchronous.
您不能真正等待.但是,通过 await
(甚至是 Promise.all()
),您可以非常接近:
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)
这篇关于等待循环完成,然后再执行下一个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文