[英]How to resolve nested promises with foreach loop inside once all data is retrieved?
I have one big promise in my function and inside I make 2 calls.我的 function 中有一个大的 promise,在里面我打了 2 个电话。 First one to get the members from the organization.第一个从组织中获取成员。 Then I iterate over it and get for each member the details + fill it into an array.然后我遍历它并为每个成员获取详细信息并将其填充到数组中。 I only want to resolve at the end, once I have detail data of each member.一旦我有每个成员的详细数据,我只想在最后解决。 I do this by comparing the lengths of the 2 arrays.我通过比较 2 个 arrays 的长度来做到这一点。 The code below works, but how can I split this or write it in a better way?下面的代码有效,但我怎样才能拆分它或以更好的方式编写它?
export const getTeamMembers = (firebaseContext, user) => {
const { activeOrganization } = user;
return new Promise((resolve, reject) => {
firebaseContext.db
.collection("organizations")
.doc(activeOrganization)
.get()
.then((snapshot) => {
if (!snapshot.empty) {
const members = snapshot.data().members;
const memberProfiles = [];
members.forEach((m) => {
firebaseContext.db
.collection("users")
.doc(m.uid)
.get()
.then((snapshot) => {
const profile = snapshot.data();
memberProfiles.push(profile);
console.log("person added");
console.log(memberProfiles);
if (members.length === memberProfiles.length) {
resolve(memberProfiles);
}
})
.catch((err) => reject(err));
});
} else {
reject([]);
}
})
.catch((err) => reject(err));
});
};
I would recommend using async/await
syntax to clean this up.我建议使用async/await
语法来清理它。 Also, you can map your code to an array of promises and await
all of them rather than doing the check in a forEach
:此外,您可以 map 将您的代码转换为一系列承诺并await
所有承诺,而不是在forEach
中进行检查:
export const getTeamMembers = async (firebaseContext, user) => {
try {
const { activeOrganization } = user;
const snapshot = firebaseContext.db
.collection("organizations")
.doc(activeOrganization)
.get();
const members = snapshot.data().members;
const memberPromises = members.map(m => {
return firebaseContext.db
.collection("users")
.doc(m.uid)
.get();
});
return (await Promise.all(memberPromises)).map(s => s.data());
} catch (e) {
// throw some error to cause promise to reject
}
};
You could maybe try this你可以试试这个
After declaring const memberProfiles = [];
在声明const memberProfiles = [];
let membersPromises = [];
members.forEach((m) => {
membersPromises.push(firebaseContext.db .collection("users") .doc(m.uid) .get());
Promise.all(membersPromises).then(profiles=>{
profiles.forEach(profile=>{
memberProfiles.push(profile.data());
});
resolve(memberProfiles);
}).catch((err) => reject(err)); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.