簡體   English   中英

我如何從此Firebase集合查詢功能中獲取“ retArr”數組。 我想將數組值用於其他功能

[英]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);
      });
    });
});

retArr具有存儲在數組中的每個城市的用戶數。 我需要在功能之外的其他地方使用此數組。 如何找回它?

您可以執行以下操作:

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
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM