简体   繁体   English

Firebase函数tslint错误必须正确处理Promise

[英]Firebase functions tslint error Promises must be handled appropriately

I am writing a firebase function using TypeScript to send push notifications to multiple users. 我正在使用TypeScript编写一个firebase函数来向多个用户发送推送通知。 But when I run firebase deploy --only functions command, TSLint gives an error "Promises must be handled appropriately". 但是当我运行firebase deploy --only functions命令时,TSLint会给出错误“必须正确处理Promise”。

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

First a remark, I think you are better of using a callable function instead of onRequest. 首先,我认为你最好使用可调用函数而不是onRequest。 See: Are Callable Cloud Functions better than HTTP functions? 请参阅: 可调用云功能是否优于HTTP功能?

Next, you need to wait for your asynchronous functions to finish before sending back the response. 接下来,您需要在发回响应之前等待异步函数完成。

In this case you are looping through all your documents returned from the query. 在这种情况下,您将循环遍历从查询返回的所有文档。 For each document you call sendToDevice. 对于每个文档,您调用sendToDevice。 This means you are executing multiple async functions in parallel. 这意味着您并行执行多个异步函数。

You can use: 您可以使用:

Promise.all([asyncFunction1, asyncFunction2, ...]).then(() => {
 response.send(`Broadcasted to ${snapshot.docs.length} users.`);
});

The following code is not tested: 以下代码未经过测试:

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

Note that I don't use the snapshot.forEach function. 请注意,我不使用snapshot.forEach函数。

Instead I prefer to use the snapshot.docs property which contains an array of all documents returned by the query and provides all normal array functions such as 'forEach' but also 'map' which I've used here to convert an array of documents into an array of promises. 相反,我更喜欢使用snapshot.docs属性,该属性包含查询返回的所有文档的数组,并提供所有常规数组函数,例如'forEach',还有'map',我在这里使用它来将文档数组转换为一系列的承诺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 这可能是什么? [TsLint 错误:“必须适当处理 Promise”] - What could this be about? [TsLint Error: “Promises must be handled appropriately”] TSLint-必须使用“ finally”适当地处理承诺 - TSLint - Promises must be handled appropriately with `finally` 必须正确处理承诺错误 - Promises must be handled appropriately error tslint 错误:jsdoc 中的 Asterik 必须对齐 - tslint error: Asterik in jsdoc must be aligned Tslint:没有子元素的 JSX 元素必须自关闭 [错误] - Tslint: JSX elements with no children must be self closing [Error] 错误的背景或推理:TsLint:注释必须以小写字母开头 - Background or reasoning for error: TsLint: comment must start with lowercase letter 什么 JS 错误有助于防止 typescript 错误返回承诺的函数必须是异步的 @typescript-eslint/promise-function-async - What JS error help prevent with typescript error when it is Functions that return promises must be async @typescript-eslint/promise-function-async 为什么mapStateToProps会发出Eslint警告“返回承诺的函数必须异步”? - Why mapStateToProps has Eslint warning 'Functions that return promises must be async'? TSLint:for 语句必须加括号(卷曲) - TSLint: for statements must be braced (curly) 当 tslint 中的“无浮动承诺”为真时如何忽略 Jasmine 承诺 - How to ignore Jasmine promises when "no-floating-promises" in tslint is true
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM