I'm currently facing an issue with an async function I've written. It takes an array of custom objects as an argument, loops through each object, retrieves data from Firestore, converts it into another custom object, and adds it to an array. The function then returns the length of this array.
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
}
However, I've noticed that this function always returns a value of 0. Looking at the console logs in Firebase, it seems that the body of the function is executed after the function has already returned the Promise of type number.
Could someone please assist me in figuring out how to make the function wait for the body to be executed before returning the length of whatsNewObjects?