db.collection("City").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
db.collection("users").where("City", "==", doc.id).get().then(function(querySnapshot) {
var jgy_usercount = querySnapshot.size;
retArr.push(jgy_usercount);
});
});
});
retArr具有存储在阵列中的每个城市的用户数。这个数组我需要在函数的其他地方使用。怎么能找回来的?
答案 0 :(得分:1)
你可以这样做:
async function getUsersPerDistrict() {
const querySnapshot = await db.collection("district").get()
const districts = []
querySnapshot.forEach(x => { districts.push(x.data) })
const districtCounts = await Promise.all(
districts.map(async x => {
const usersFromDistrict = await db.collection("users").where("City", "==", x.id).get()
return { count: usersFromDistrict.size, name: x.name }
})
)
return districtCounts
}
没有async / await:
function getUsersPerDistrict() {
return db.collection("district").get().then(querySnapshot => {
const districts = []
querySnapshot.forEach(x => { districts.push(x.data) })
const districtCounts = Promise.all(
districts.map(x =>
db.collection("users").where("City", "==", x.id).get()
.then(usersFromDistrict => ({
count: usersFromDistrict.size,
name: x.name
}))
)
)
return districtCounts
}