我想在firebase实时数据库中创建对象确认的登高时,向所有确认访客发送通知。
因此,我首先创建了来自确认的登高对象的所有用户的数组。然后,我迭代所有这些用户,并将他们的DeviceTokens推到一系列DeviceTokens上。预计数组alldevicetokens将是确认登记中所有用户的设备令牌的数组。
但是,当创建确认的登记对象时,该函数会返回错误。
下面是我的云功能
exports.sendNotification = functions.database
.ref('/feed/{pushId}/confirmedGuests')
.onCreate((snapshot, context) => {
const pushId = context.params.pushId;
if (!pushId) {
return console.log('missing mandatory params for sending push.')
}
let allDeviceTokens = []
let guestIds = []
const payload = {
notification: {
title: 'Your request has been confirmed!',
body: `Tap to open`
},
data: {
taskId: pushId,
notifType: 'OPEN_DETAILS', // To tell the app what kind of notification this is.
}
};
let confGuestsData = snapshot.val();
let confGuestItems = Object.keys(confGuestsData).map(function(key) {
return confGuestsData[key];
});
confGuestItems.map(guest => {
guestIds.push(guest.id)
})
for(let i=0; i<guestIds.length; i++){
let userId = guestIds[i]
admin.database().ref(`/users/${userId}/deviceTokens`).once('value', (tokenSnapshot) => {
let userData = tokenSnapshot.val();
let userItem = Object.keys(userData).map(function(key) {
return userData[key];
});
userItem.map(item => allDeviceTokens.push(item))
})
}
return admin.messaging().sendToDevice(allDeviceTokens, payload);
});
您正在从实时数据库中加载每个用户的设备令牌:
admin.database().ref(`/users/${userId}/deviceTokens`).once('value', (tokenSnapshot) => {
此负载操作异步发生。这意味着到admin.messaging().sendToDevice(allDeviceTokens, payload)
调用运行时,尚未加载令牌。
要解决此问题,您需要等到所有令牌加载,然后拨打sendToDevice()
。这样做的常见方法是使用Promise.all()
let promises = [];
for(let i=0; i<guestIds.length; i++){
let userId = guestIds[i]
let promise = admin.database().ref(`/users/${userId}/deviceTokens`).once('value', (tokenSnapshot) => {
let userData = tokenSnapshot.val();
let userItem = Object.keys(userData).map(function(key) {
return userData[key];
});
userItem.map(item => allDeviceTokens.push(item))
return true;
})
promises.push(promise);
}
return Promise.all(promises).then(() => {
return admin.messaging().sendToDevice(allDeviceTokens, payload);
})