簡體   English   中英

Firebase函數tslint錯誤必須正確處理Promise

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

我正在使用TypeScript編寫一個firebase函數來向多個用戶發送推送通知。 但是當我運行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);
    })
});

首先,我認為你最好使用可調用函數而不是onRequest。 請參閱: 可調用雲功能是否優於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',我在這里使用它來將文檔數組轉換為一系列的承諾。

暫無
暫無

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

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