【发布时间】:2019-10-28 16:58:35
【问题描述】:
我想在 Firebase 函数中完成什么:
- 从 Firebase 数据库电子邮件地址读取到批量电子邮件。
- 遍历每一个并发送电子邮件。
我在完成我认为的承诺时遇到了问题。这些不需要按顺序运行,我只需要在结束前解决所有的承诺。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const https = require('axios');
exports.sendEmail = functions.pubsub.topic('nightly_topic').onPublish(() => {
let emailsToSend = [];
async function getTests (){
admin.firestore()
.collection("tests")
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
emailsToSend.push(doc.data())
});
})
.catch(function (error) {
console.error(error);
});
}
async function send (address){
let body = {
//MANDRILL INFO REMOVED
};
let endpoint = 'https://mandrillapp.com/api/1.0/messages/send-template.json';
https.post(endpoint, body)
.then((result) => {
console.log('SUCCESS');
})
.catch(function (error) {
console.error(error);
});
}
async function init() {
await getTests();
for (const email of emailsToSend) {
await send(email.address);
}
}
init();
});
【问题讨论】:
-
您的函数需要返回一个承诺,该承诺会在您的函数中的所有异步工作完成时解决。现在,您的函数没有返回任何内容。
-
是的@DougStevenson,这就是我的问题中的问题描述。
-
听起来你明白如何继续。你有什么特别的问题吗?
-
@DougStevenson 如果您愿意提供帮助,请再次阅读该问题 - 我无法确定我在哪里错过了 Promise 回报和解决方案。如果您只是来这里钓鱼,请查找另一个帖子。
-
我只是想确保您理解错误消息的含义。您应该研究使用
Promise.all()创建一个新的 Promise 来解决或拒绝您正在使用的所有其他 Promise
标签: javascript node.js firebase promise google-cloud-functions