簡體   English   中英

Firestore function 雲消息傳遞無法正常工作

[英]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;

如果您想捕獲返回 promise 的調用錯誤,您應該使用 try/catch 來繞過await的使用。

我強烈建議您花時間學習如何有效地使用 Promise,否則您在實現 Cloud Functions 代碼時會不斷遇到類似這樣的奇怪錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM