我创建了一个云函数,它进入名为“properties”的 firebase 集合,然后进入名为“mid_tenancy”的特定属性中的子集合。在“mid_tenancy”的 id 中,我然后遍历租户的每个成员并访问他们的电子邮件。
但是,我遇到的问题是,电子邮件只发送到循环中的第一封电子邮件,而不是其他任何一封。这是我的数据库的样子:
出于显而易见的原因,我删除了这些电子邮件
这是我的云函数:
export const midTenancyEmail = functions.firestore
.document('properties/{propertyId}/mid_tenancy/{midTenancyId}')
.onCreate(event => {
const propertyId = event.params.propertyId;
const midTenancyId = event.params.midTenancyId;
const db = admin.firestore();
const propertyDoc = db.collection('properties').doc(propertyId);
const midTenancyDoc = propertyDoc.collection('mid_tenancy').doc(midTenancyId);
let mid_tenancy;
return propertyDoc
.get()
.then(doc => {
const property = doc.data();
midTenancyDoc.get().then(data => {
mid_tenancy = data.data();
for(let tenant of mid_tenancy.mid_tenants) {
let msg = {
to: tenant.mid_tenant_email,
from: 'email',
// custom templates
subject: 'You have a new direct message',
templateId: 'id',
substitutionWrappers: ['{{', '}}'],
substitutions: {
name: tenant.mid_tenant_name,
message: tenant.status,
}
};
return sgMail.send(msg);
}
})
})
.then(email => {
console.log('email sent: ', email);
})
.catch(err => {
console.log(err);
})
});
有人知道为什么只发送一封电子邮件吗?而不是循环中的所有电子邮件?在第一个循环之后似乎有什么东西打破了循环。
在循环之前我已经完成了:console.log(mid_tenancy.mid_tenants[1].mid_tenant_name
只是为了确保它可以访问,并且它确实记录了。
最佳答案
您需要将每个电子邮件任务推送到一个 promise 数组中,然后返回所有 promise return Promise.all(promises)
:
export const midTenancyEmail = functions.firestore
.document('properties/{propertyId}/mid_tenancy/{midTenancyId}')
.onCreate(event => {
const propertyId = event.params.propertyId;
const midTenancyId = event.params.midTenancyId;
const db = admin.firestore();
const propertyDoc = db.collection('properties').doc(propertyId);
const midTenancyDoc = propertyDoc.collection('mid_tenancy').doc(midTenancyId);
let mid_tenancy;
return propertyDoc
.get()
.then(doc => {
const property = doc.data();
midTenancyDoc.get().then(data => {
mid_tenancy = data.data();
const promises = [];
for (let tenant of mid_tenancy.mid_tenants) {
let msg = {
to: tenant.mid_tenant_email,
from: 'email',
// custom templates
subject: 'You have a new direct message',
templateId: 'id',
substitutionWrappers: ['{{', '}}'],
substitutions: {
name: tenant.mid_tenant_name,
message: tenant.status,
}
};
promises.push(sgMail.send(msg)) ;
}
return Promise.all(promises);
});
return null;
})
.catch(err => {
console.log(err);
});
});
关于javascript - 向循环 firebase 云功能中的所有电子邮件发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51286039/