I was wondering if someone could help enlighten me as to how I can successfully execute this code where it waits until the entire array is filled with FCM tokens before firing sendToDevice()
.
I've been using these links (listed below) as references to try and resolve this but I still can not figure it out so alas here I am on SO seeking guidance. I just need to pass the tokens
array once it is filled completely. I've gotten it where it fired multiple times on each push
but never where it asynchronously loads and then fires ><
Firebase Real Time Database Structure for File Upload
Promise.all with Firebase DataSnapshot.forEach
https://aaronczichon.de/2017/03/13/firebase-cloud-functions/
exports.sendVenueAnnouncement = functions.database.ref(`/venueAnnouncements/{venueUid}/announcement`).onCreate(event => {
const venueUid = event.params.venueUid;
const announcement = event.data.val();
const getVenueDisplaynamePromise = admin.database().ref(`verifiedVenues/${venueUid}/displayname`).once('value');
return getVenueDisplaynamePromise.then(snapshot => {
const displayname = snapshot.val();
const payload = {
notification: {
title: `${displayname}`,
body: `${announcement}`
}
};
const getSubscriberTokensPromise = admin.database().ref(`subscribers/${venueUid}`).once('value');
return getSubscriberTokensPromise.then(snapshot => {
const tokens = [];
snapshot.forEach(function(childSnapshot) {
const key = childSnapshot.key;
const token = admin.database().ref(`pushTokens/` + key).once('value');
tokens.push(token);
});
return Promise.all(tokens);
}, function(error) {
console.log(error.toString())
}).then(function(values) {
return admin.messaging().sendToDevice(values, payload).then(response => {
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {
tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove)
});
})
})
})