javascript - 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);
});
解决方案
您在调用 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 代码时会不断遇到类似这样的奇怪错误。
推荐阅读
- java - 如何将本机查询结果映射到自定义类对象?
- excel - 试图制作一个公式来识别另一个是否为空白,然后添加一个数字 [Excel]
- python - 在同一前缀上注册多个 restplus 蓝图不起作用
- apache-camel - 防止 Apache AHC 向请求中添加“transfer-encoding:chunked”标头
- vue.js - 在 axios 调用时,DOM 不显示 vue.js 和 laravel 中数组的更新数据
- python - 如何找到将列拆分为两个新行的行?
- javascript - 无法在 javascript 中的模块外使用 import 语句
- algorithm - 需要帮助模拟基本导弹 - 目标模拟(算法 - 首选 Qbasic)
- git - git rebase -i HEAD~2 的问题
- graphql - 如何从 graphql 查询的 Contentful 内容类型获取 SYS 数据?