[英]How to wait for an async query to finish in a for loop?
I want to get the result of an async function - depending on the result I either want to execute another function or continue the for loop.我想获得异步函数的结果 - 根据结果,我要么想执行另一个函数,要么继续 for 循环。 Here is my Cloud Function:
这是我的云功能:
return query.get().then(geoSnapshot => {
// If GeoquerySnapshot returns 0 docs, createDoc()
let docs = geoSnapshot.docs;
if (docs.length === 0) return createDoc(data);
for(let [index, doc] of docs.entries()){
// If age preferences are valid, joinDoc
let currentDoc = docs[index].data();
if (validAge(currentDoc, data)){
let matchedBefore = await(matchedBefore(currentDoc, data))
if (!matchedBefore){
return joinDoc(docs[index], data);
} else if (index === (docs.length - 1)) {
return createDoc(data);
}
}
return
}
}).catch( error => {
console.log("error query: " + error);
return { error: error };
})
async function matchedBefore(currentDoc, data){
return db.collection('users').doc(data.uid).get().then( doc => {
if ( !doc.exists ) return false;
// If user1 in matchedUsers
let matchedUsers = doc.get('matchedUsers');
if (matchedUsers === undefined) return true
let matchedBefore = matchedUsers.includes(currentDoc.user1);
console.log('matchedBefore: ' + matchedBefore);
if (matchedBefore) {
return false
} else {
return true
}
})
}
I'm getting this following error on let matchedBefore = await(matchedBefore(currentDoc, data))
:我在
let matchedBefore = await(matchedBefore(currentDoc, data))
上遇到以下错误:
Each then() should return a value or throw
How can I ensure the function matchedBefore()
finishes before the for loop continues?如何确保函数
matchedBefore()
在for 循环继续之前完成?
I think you are too confused with the implementation of async-await.我认为您对 async-await 的实现太困惑了。 The correct way would be:
正确的方法是:
return query.get().then(async geoSnapshot => { // If GeoquerySnapshot returns 0 docs, createDoc() let docs = geoSnapshot.docs; if (docs.length === 0) return createDoc(data); /* eslint-disable no-await-in-loop */ for(let [index, doc] of docs.entries()) { // If age preferences are valid, joinDoc let currentDoc = docs[index].data(); if (validAge(currentDoc, data)){ let matchedBefore = await(matchedBefore(currentDoc, data)) if (!matchedBefore){ return joinDoc(docs[index], data); } else if (index === (docs.length - 1)) { return createDoc(data); } } return } /* eslint-enable no-await-in-loop */ }).catch( error => { console.log("error query: " + error); return { error: error }; }) async function matchedBefore(currentDoc, data){ let doc = await db.collection('users').doc(data.uid).get() if ( !doc.exists ) return false; // If user1 in matchedUsers let matchedUsers = doc.get('matchedUsers'); if (matchedUsers === undefined) return true let matchedBefore = matchedUsers.includes(currentDoc.user1); console.log('matchedBefore: ' + matchedBefore); return !matchedBefore }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.