0
votes

What I am trying to do is run a job when at specific time it will fetch a specific field from my document and send a notification to the user using the fetched contents.

But the problem is notification body remains empty. I tried to log if whatever I am fetching from the documents are empty or not. But as per the logs the logs the quote variable is not empty.

Please point me what I am missing

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

});
1

1 Answers

1
votes

You're not using promises correctly on the call to Firestore. Calling then doesn't pause the code like await does. Your code will simply immediately move on to the call to FCM before waiting for the query to finish.

You should instead use await again to pause your code to wait for the result of get().

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

If you want to catch error on a call the returns a promise, you should use try/catch around the use of await.

I strongly suggest taking time to learn how to use promises effectively, or you will keep running into strange errors like this when implementing Cloud Functions code.