如何在firebase数据检索过程中等待foreach


async onclick(){
let number=this.state.phoneNumber
if(number !== null && number.length===10){
console.log('number',number)
await firestore().collection('profile')
.where('mobile', '==', number).get().then(snapshot => {
if (snapshot.empty) {
}
else{
console.log(snapshot.data())

const res=Promise.resolve(async function(){
let data=[]
await  snapshot.forEach(doc => {
data.push({data:doc.data().uid})
})
return data
})
if(res.length !==0){
res.then((pra)=>{
let payload={Requester:auth().currentUser.uid,Responder:pra}
firestore().collection('requests').add(payload).then(function() {
goHome();
});
})
}
}
})
}
else{
showSnackbar('Please enter valid mobile number');
}
}

这是我的代码这里我想等待foreach完成之后这是想保存从这个foreach接收到的数据到firebase但问题是,在foreach完成之前它正在运行查询所以我在firebase中得到空数据

问题不是async/await,您的res是一个承诺,长度将始终未定义。例如:

var p = Promise.resolve([1,2,3]);
console.log(p.length) // undefined

你能试着改正一下吗?

const res = await Promise.all( snapshot.map( doc => doc.data().uid ) );

最新更新