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你解决了我的问题,我获得了知识。谢谢 –

相关问题