简体   繁体   中英

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?

You could do something like this:

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM