0

我試圖讓多個推送通知在Firebase的雲端函數上運行,但沒有成功。Firebase雲端函數發送推送給多個用戶

我存儲我的消息收據中的一個節點

  • message_receipts
    • -KtvyTN3nbVKoFjHdpJg
    • hHhs5Aco38X1W8EhaaxrwsQDXwy1: 「收據」
    • nI25FjUnBfQiCWzdCUIAe8CWTPQ2: 「收據」

要發送的雲功能,我嘗試下面的推送通知:

//*********************************************************************************************************** */ 
//handle lsit item added by shared user 
if (String(msgData.messageType) == 'ListItemAddedBySharedUser') { 

    return admin.database().ref("message_receipts").child(event.params.messageID).once('value').then(receipts => { 

     receipts.forEach(function (receipt) { 

      //Send push to receipt 
      return admin.database().ref('/users/' + receipt.key).once('value').then(usnap => { 

       //Send push to users fcmToken 
       const userSnap = usnap.val() 
       console.log('sending Push to ' + userSnap.fcmToken) 


       //create Notification Payload 
       var payload = { 
        notification: { 
         title: msgData.title, 
         body: msgData.message, 
         badge: '1', 
         sound: 'default', 
         sbID: String(event.data.key), 
         senderID: msgData.senderID, 
         listID: msgData.listID, 
         receiptID: receipt.key, 
         notificationType: String(msgData.messageType), 
        } 
       }; 

       return admin.messaging().sendToDevice(userSnap.fcmToken, payload).then(response => { 

        console.log("Successfully sent invite message:", response) 
        console.log(response.results[0].error) 

       }).catch((err) => { console.log("Error sending Push", err) }) 

      }) 

     }) 

    }) 
} //*********************************************************************************************************** */ 

我得到的是一個發送通知。 我很新的Java腳本和雲功能。 如何通知我的所有用戶需要做些什麼?

+0

嗨有, 做你介意發佈你完成的解決方案嗎?很想看到它。 – Gugulethu

回答

0

您需要彙總所有正在執行的異步操作。在這裏,你正在對郵件收據做一個forEach,但是你將返回一個單一的承諾。嘗試是這樣的:

var promises = []; 
receipts.forEach(function (receipt) { 
    //Send push to receipt 
    promises.push(admin.database().ref('/users/' + receipt.key).once('value').then(usnap => { 
     /* ... */ 
    })) 
}) 

return Promise.all(promises); 

這將聚集所有的優秀通知到一個單一的電話Promise.all,這將等待,直到他們全部完成。

+0

大@Michel Bleigh你解決了我的問題,我獲得了知識。謝謝 –

相關問題