javascript - How do i get the "retArr" array out from this firebase collection query function. I want the array values to used for another function
问题描述
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);
});
});
});
The retArr has the number of users per city that is stored in the array. this array i need to use elsewhere out of the function. How can retrieve it?
解决方案
你可以这样做:
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
}
没有异步/等待:
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
}
推荐阅读
- python-3.x - 解析xml文件pandas df
- matlab - 如何在 MATLAB 中绘制相量
- flutter - 如何在颤动中将国家拨号代码添加到 TextEditingController
- html - 如何将数据从一个 React.js 文件传递到另一个文件?
- firebase-authentication - 使用 Firebase UID 作为用户的数据存储区密钥名称是不是一个坏主意?
- c# - 如何在 xunit 中测试是否引发了 Event?
- python - PySide2 应用程序使用的字体是否与 PyInstaller 一起打包?
- r - 返回此错误的聚合子集:强制引入的 NA
- c# - REST API 授权最佳实践
- excel - 如何在 Windows 的同一个 Excel 单元格中键入东方阿拉伯数字和阿拉伯字母?