gpt4 book ai didi

javascript - 如何在 for 循环中等待异步查询完成?

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:42 27 4
gpt4 key购买 nike

我想要获取异步函数的结果 - 根据结果,我要么想要执行另一个函数,要么继续 for 循环。这是我的云功能:

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
}
})
}

我在 let matchesBefore = wait(matchedBefore(currentDoc, data)) 上收到以下错误:

Each then() should return a value or throw

如何确保函数 matchedBefore() 在 for 循环继续之前完成?

最佳答案

我认为你对 async-await 的实现太困惑了。正确的做法是:

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
}

关于javascript - 如何在 for 循环中等待异步查询完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59893640/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com