I have a function that maps each element of an array (email addresses in this case), yielding an array of promises that should resolve to document ids automatically generated by Firebase (i.e. hAvJ3qPq821tq1q2rrEv, 0tjeKB1aW8jsOAse5fcP).
async function addMultipleParticipants(participant_emails: Array<string>) {
console.log("Parallelizing participant processing");
const promises = participant_emails.map(addParticipant);
const document_ids = await Promise.all(promises);
console.log("Final document ids: " + document_ids);
return document_ids;
};
Here is the function that returns the document ids, depending on whether it could find an existing document associated with the email address or needed to create a new document.
async function addParticipant(email_address: string) {
try {
console.log("Querying for person");
const query = await db.collection('people')
.where('emails', 'array-contains', email_address)
.limit(1);
const querySnapshot = await query.get();
if (!querySnapshot.empty) {
console.log("Document exists for email " + email_address);
// TODO: There is only one, so we shouldn't have to iterate
querySnapshot.forEach(function(docRef: any) {
console.log("New document id: " + docRef.id);
const document_id = docRef.id;
return document_id;
});
} else {
console.log("Creating person with " + email_address);
const fields = {emails: [email_address]};
try {
const docRef = await db.collection('people').add(fields);
console.log("New document id: " + docRef.id);
const document_id = docRef.id;
return document_id;
} catch (err) {
console.log("Error adding document:", err);
}
}
} catch (err) {
console.log("Error getting document:", err);
}
};
When all participant emails don't exist in documents yet, the functions work as expected, and console.log() outputs Final document ids: hAvJ3qPq821tq1q2rrEv, 0tjeKB1aW8jsOAse5fcP.
However, when at least one email address is associated with an existing document, the promises from addParticipant() do not resolve to anything, and console.log() outputs Final document ids: ,.
In this scenario, what do I need to do to ensure that the array of promises resolves properly in addMultipleParticipants()?