【发布时间】:2023-04-01 03:22:01
【问题描述】:
我很难让 Promise 链在 Firebase 云函数中正确流动。它遍历一个 ref 并返回一组用于发送通知的电子邮件。它有一些嵌套的孩子,我认为这就是我出错的地方,但我似乎找不到错误。
/课程结构
{
123456id: {
..
members: {
uidKey: {
email: some@email.com
},
uidKey2: {
email: another@email.com
}
}
},
some12345string: {
// no members here, so skip
}
}
function.js
exports.reminderEmail = functions.https.onRequest((req, res) => {
const currentTime = new Date().getTime();
const future = currentTime + 172800000;
const emails = [];
// get the main ref and grab a snapshot
ref.child('courses/').once('value').then(snap => {
snap.forEach(child => {
var el = child.val();
// check for the 'members' child, skip if absent
if(el.hasOwnProperty('members')) {
// open at the ref and get a snapshot
var membersRef = admin.database().ref('courses/' + child.key + '/members/').once('value').then(childSnap => {
console.log(childSnap.val())
childSnap.forEach(member => {
var email = member.val().email;
console.log(email); // logs fine, but because it's async, after the .then() below for some reason
emails.push(email);
})
})
}
})
return emails // the array
})
.then(emails => {
console.log('Sending to: ' + emails.join());
const mailOpts = {
from: 'me@email.com',
bcc: emails.join(),
subject: 'Upcoming Registrations',
text: 'Something about registering here.'
}
return mailTransport.sendMail(mailOpts).then(() => {
res.send('Email sent')
}).catch(error => {
res.send(error)
})
})
})
【问题讨论】:
标签: javascript firebase google-cloud-functions