首页 > 解决方案 > Firestore 功能云消息传递无法正常工作

问题描述

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

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

请指出我所缺少的

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

});

标签: javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functionsfirebase-cloud-messaging

解决方案


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

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

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

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

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


推荐阅读