【问题标题】:Firestore function cloud messaging not working properlyFirestore 功能云消息传递无法正常工作
【发布时间】:2020-11-28 20:50:41
【问题描述】:

我要做的是在特定时间运行作业,它将从我的文档中获取特定字段并使用获取的内容向用户发送通知。

但问题是通知正文仍然是空的。我试图记录我从文档中获取的内容是否为空。但是根据日志,引用变量不为空。

请指出我错过了什么

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);

});

【问题讨论】:

    标签: javascript firebase google-cloud-firestore google-cloud-functions firebase-cloud-messaging


    【解决方案1】:

    您在调用 Firestore 时未正确使用 Promise。调用then 不会像await 那样暂停代码。在等待查询完成之前,您的代码将立即转到对 FCM 的调用。

    您应该再次使用 await 来暂停您的代码以等待 get() 的结果。

        const snapper = await admin.firestore().collection('quotes').doc(dateQry).get()
        quote = snapper.data().english;
    

    如果你想在调用返回一个 promise 时捕获错误,你应该在 await 周围使用 try/catch。

    我强烈建议您花时间学习如何有效地使用 Promise,否则您在实现 Cloud Functions 代码时会不断遇到此类奇怪的错误。

    【讨论】:

    • 谢谢,我实际上正在努力学习,但有时 youtube 视频甚至文档都无法理解,所以我希望你能理解
    • 坦率地说 - Firebase 产品的 YouTube 教程并不是学习编程语言的好方法。这些教程通常假设您已经了解该语言。我建议先努力学习 JavaScript,然后再尝试使用 Cloud Functions 进行复杂的操作。
    • 再次感谢您的指导
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2020-05-18
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    相关资源
    最近更新 更多