typescript - Firebase 函数 tslint 错误 必须正确处理承诺
问题描述
我正在使用 TypeScript 编写一个 firebase 函数来向多个用户发送推送通知。但是当我运行firebase deploy --only functions
命令时,TSLint 会给出错误“必须正确处理承诺”。
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
export const broadcastJob = functions.https.onRequest((request, response) => {
const db = admin.firestore();
db.collection('profiles').get().then(snapshot => {
snapshot.forEach(doc => {
const deviceToken = doc.data()['deviceToken'];
admin.messaging().sendToDevice(deviceToken, { //<-- Error on this line
notification: {
title: 'Notification',
body: 'You have a new notification'
}
});
});
response.send(`Broadcasted to ${snapshot.docs.length} users.`);
}).catch(reason => {
response.send(reason);
})
});
解决方案
首先说一句,我认为你最好使用可调用函数而不是 onRequest。请参阅:Callable Cloud Functions 是否比 HTTP 函数更好?
接下来,您需要等待异步函数完成,然后再发回响应。
在这种情况下,您将遍历从查询返回的所有文档。对于您调用 sendToDevice 的每个文档。这意味着您正在并行执行多个异步函数。
您可以使用:
Promise.all([asyncFunction1, asyncFunction2, ...]).then(() => {
response.send(`Broadcasted to ${snapshot.docs.length} users.`);
});
以下代码未经测试:
export const broadcastJob = functions.https.onRequest((request, response) => {
const db = admin.firestore();
db.collection('profiles').get().then(snapshot => {
Promise.all(snapshot.docs.map(doc => {
const deviceToken = doc.data()['deviceToken'];
return admin.messaging().sendToDevice(deviceToken, {
notification: {
title: 'Notification',
body: 'You have a new notification'
}
});
})).then(() => {
response.send(`Broadcasted to ${snapshot.docs.length} users.`);
}
}).catch(reason => {
response.send(reason);
})
});
请注意,我不使用 snapshot.forEach 函数。
相反,我更喜欢使用 snapshot.docs 属性,它包含查询返回的所有文档的数组,并提供所有正常的数组函数,例如“forEach”,还提供“map”,我在这里使用它来将文档数组转换为一系列承诺。
推荐阅读
- python - 在 MySQL 中存储印地语
- google-apps-script - 有没有什么地方或方法可以在谷歌应用脚本中存储私钥?
- android - Android 10 中的剪贴板未按预期工作
- sql-server - 如何将 DD/MM/YYYY 插入 SQL Server DATE 格式?
- mysql - Delphi 现有应用程序连接到云
- sql - 在连接两个表期间获取最大总和
- ios - Apple SSD 的 Used Memory 在运行 Xcode 项目时不断增加
- ios - 为什么设置 UIBarButtonItem 的 primaryAction 属性会更改其图像?
- php - 无法在 php 联系表单代码中显示错误或成功消息
- python - 打开 Cv 将珠宝图像添加到捕获的面部问题