【发布时间】:2020-12-08 10:04:28
【问题描述】:
所以我有一个异步函数,它接受一组自定义对象作为参数,然后遍历每个对象并从 firestore 获取一些数据。 Firestore 中的数据被转换为另一个自定义对象,并添加到另一个自定义对象数组中。这些对象的长度由函数返回。
async function getCompsReceived(theInterestedPeople: InterestedPerson[]) {
const whatsNewObjects: WhatsNewObject[] = []
theInterestedPeople.forEach(async (person) => {
const documentsSnapshot = await
db.collection('Users').doc(person.uid).collection('complimentsReceived')
.orderBy('receivedTime', 'desc')
.limit(documentLimit)
.get()
if (documentsSnapshot.empty) {
console.log(`${person.userName} has no compsReceived`)
return
}
await documentsSnapshot.forEach((newCompReceived: { receiverUid: string; receiverUserName: string;
complimentsReceivedContent: string | null; hasImage: boolean | null; senderUid: string | null;
senderUserName: string | null; noOfLikes: number | null; receivedTime: number | null;
complimentId: string | null} ) => {
//Add each new Compliment to the WhatsNewObjects Array
const whatsNewDoc = new WhatsNewObject(
newCompReceived.receiverUid,
newCompReceived.receiverUserName,
true,
newCompReceived.complimentsReceivedContent,
newCompReceived.hasImage,
newCompReceived.senderUid,
newCompReceived.senderUserName,
newCompReceived.noOfLikes,
newCompReceived.receivedTime,
newCompReceived.complimentId,
'PERSON_COMPLIMENT_RECEIVED'
)
whatsNewObjects.push(whatsNewDoc)
})
console.log(`length of whatsNewObjects after adding ${person.userName}'s compsReceived is
${whatsNewObjects.length}`)
})
console.log(`returning the length of WhatsNewObjects at getCompsReceived which is ${whatsNewObjects.length}}`)
return whatsNewObjects.length
}
问题是这个函数总是返回 0 并且在 Firebase 控制台上打印日志语句,我看到函数的主体在函数已经返回一个类型为 number 的 Promise 值之后被执行。
有人可以帮助我如何让函数在返回 whatsNewObjects.length 之前等待主体执行?
【问题讨论】:
标签: typescript firebase async-await google-cloud-functions