在foreach完成之前发送响应

时间:2019-10-19 19:48:46

标签: typescript firebase async-await google-cloud-functions nuxt

我正在尝试获取一个带有其子集合的Firestore集合。 因此,我编写了一个Firestore Cloud Function。但是,当我发送请求时,我得到了一个空数组。发送响应后,控制台日志将显示数据。

谁能向我解释:我在做什么错了?

我知道代码不是最佳实践,但是如果有人对如何获取数据有更好的了解。希望能听到。谢谢

我的代码:

export const helloWorld = functions.https.onRequest((request, response) => {
  cors(request, response,() => {
    getProfiles()
      .then((data) => {
        console.log(data)
        response.send(data)
      })
      .catch((err) => {
        console.log(err)
      })
  })
})

const getProfiles = async (): Promise<any[]> => {
  const allTrainers: any[] = []
  const trainerProfiles = await db.collection('consultant_profiles').get()

  trainerProfiles.forEach(async (snapshot: DocumentSnapshot) => {
    const profile = snapshot.data()

    if (profile) {
      profile['.key'] = snapshot.id
    }

    const trainerPackets = await db
      .collection('consultant_profiles')
      .doc(snapshot.id)
      .collection('consultant_packets')
      .orderBy('price', 'asc')
      .get()

    const packets: any[] = []
    trainerPackets.forEach((packet: DocumentSnapshot) => {
      packets.push(packet.data())
    })

    const trainerReviews = await db
      .collection('consultant_profiles')
      .doc(snapshot.id)
      .collection('consultant_reviews')
      .get()

    const reviews: any[] = []
    trainerReviews.forEach((review: DocumentSnapshot) => {
      reviews.push(review.data())
    })

    allTrainers.push(profile, packets, reviews)

    console.log(profile, packets, reviews)
  })

  return allTrainers
}

日志:

[]
9:21:44.586 PM
helloWorld
Function execution took 2717 ms, finished with status code: 200
9:21:44.889 PM
helloWorld
[]
9:21:44.893 PM
helloWorld
Function execution took 1291 ms, finished with status code: 200
9:21:49.268 PM
helloWorld
{ updatedAt: Timestamp { _seconds: 1568747857, _nanoseconds: 790000000 }, first_name: 'Torben', services: [ 'nutrition', 'fitness', 'health' ], description: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.', image_url: 'https://www.fillmurray.com/360/360', last_name: 'Müller', '.key': 'VajLDpnbNPPJ3WjR0tKRBZ8bKX63' } [ { userId: 'VajLDpnbNPPJ3WjR0tKRBZ8bKX63', description: 'Drittes Paket ALL INC', price: 89, createdAt: Timestamp { _seconds: 1568747856, _nanoseconds: 878000000 } } ] []

1 个答案:

答案 0 :(得分:2)

您可以按以下方式使用Promise.all

...

await Promise.all(trainerProfiles.map(async (snapshot: DocumentSnapshot) => {
    ...
    return true;
}))

return allTrainers

希望对您有帮助。