Firestore 功能云消息传递无法正常工作
Firestore function cloud messaging not working properly
我想做的是 运行 一项工作,它会在特定时间从我的文档中获取特定字段并使用获取的内容向用户发送通知。
但问题是通知正文仍然是空的。我试图记录我从文档中获取的内容是否为空。但是根据日志,引用变量不为空。
请指出我缺少的内容
exports.sendDailyQuotes = functions.pubsub.schedule('0 7 * * *').timeZone('Asia/Kolkata').onRun(async (context) => {
var today = new Date();
today.setDate(today.getDate() + 1);
var currMonth = today.getMonth() + 1;
var dateQry = today.getDate() + "-" + currMonth;
var quote;
admin.firestore().collection('quotes').doc(dateQry).get().then(snapper => {
quote = snapper.data().english;
return "";
}).catch(reason => {
console.log(reason);
});
var dailyQuote = {
notification : {
title : "Daily Quote",
body : quote, //This is staying empty
},
topic : 'notifications'
}
let response = await admin.messaging().send(dailyQuote);
console.log(response);
});
您在调用 Firestore 时没有正确使用承诺。调用 then
不会像 await
那样暂停代码。在等待查询完成之前,您的代码将立即继续调用 FCM。
您应该再次使用 await 来暂停您的代码以等待 get()
的结果。
const snapper = await admin.firestore().collection('quotes').doc(dateQry).get()
quote = snapper.data().english;
如果你想在调用 returns 承诺时捕获错误,你应该使用 try/catch 围绕 await
.
的使用
我强烈建议您花时间学习如何有效地使用 promises,否则您将 运行 在实施 Cloud Functions 代码时陷入类似这样的奇怪错误。
我想做的是 运行 一项工作,它会在特定时间从我的文档中获取特定字段并使用获取的内容向用户发送通知。
但问题是通知正文仍然是空的。我试图记录我从文档中获取的内容是否为空。但是根据日志,引用变量不为空。
请指出我缺少的内容
exports.sendDailyQuotes = functions.pubsub.schedule('0 7 * * *').timeZone('Asia/Kolkata').onRun(async (context) => {
var today = new Date();
today.setDate(today.getDate() + 1);
var currMonth = today.getMonth() + 1;
var dateQry = today.getDate() + "-" + currMonth;
var quote;
admin.firestore().collection('quotes').doc(dateQry).get().then(snapper => {
quote = snapper.data().english;
return "";
}).catch(reason => {
console.log(reason);
});
var dailyQuote = {
notification : {
title : "Daily Quote",
body : quote, //This is staying empty
},
topic : 'notifications'
}
let response = await admin.messaging().send(dailyQuote);
console.log(response);
});
您在调用 Firestore 时没有正确使用承诺。调用 then
不会像 await
那样暂停代码。在等待查询完成之前,您的代码将立即继续调用 FCM。
您应该再次使用 await 来暂停您的代码以等待 get()
的结果。
const snapper = await admin.firestore().collection('quotes').doc(dateQry).get()
quote = snapper.data().english;
如果你想在调用 returns 承诺时捕获错误,你应该使用 try/catch 围绕 await
.
我强烈建议您花时间学习如何有效地使用 promises,否则您将 运行 在实施 Cloud Functions 代码时陷入类似这样的奇怪错误。