我有一个函数映射数组的每个元素(在本例中为电子邮件地址),生成一个应解析为 Firebase 自动生成的文档 ID 的 promise 数组(即 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;
};
这是返回文档 ID 的函数,具体取决于它是否可以找到与电子邮件地址关联的现有文档或创建新文档所需的文档。
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);
}
};
当文档中还没有所有参与者的电子邮件时,函数会按预期工作,并且 console.log()
输出 Final document ids: hAvJ3qPq821tq1q2rrEv, 0tjeKB1aW8jsOAse5fcP
。
但是,当至少一个电子邮件地址与现有文档相关联时,addParticipant()
的 promise 不会解决任何问题,并且 console.log()
输出 Final document ids: ,
.
在这种情况下,我需要做什么来确保 promise 数组在 addMultipleParticipants()
中正确解析?
最佳答案
When all participant emails don't exist in documents yet, the functions work as expected, and console.log() outputs Final document ids: hAvJ3qPq821tq1q2rrEv, 0tjeKB1aW8jsOAse5fcP
这是因为它解析为以下返回语句:
return document_id;
However, when at least one email address is associated with an existing document, the promises from addParticipant() do not resolve to anything
因为它不返回任何东西。你的最后一句话是:
// 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;
});
它不是返回任何 id。它只是一个forEach
。修复示例如下:
// Return the id
return querySnapshot[0].document_id;
关于javascript - typescript promise 数组在一种情况下正确解决但在另一种情况下不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55213189/