Firebase云功能有时无法正常工作
以下功能是我正在用于向用户发送通知。
function sendNotification(userID,payload){
let collectionReference = userCollection.doc(userID).collection('deviceToken').doc(documentName)
console.log('Notification userID:', userID);
console.log('Notification payload:',payload);
return collectionReference.get().then(doc => {
if (!doc.exists) {
console.log(`Notification sent failed: This user ${userID} does not have device token!`);
}else{
let data = doc.data()
console.log('User found in database....');
if(data.token !== undefined){
console.log('Token found in database....'+data.token);
admin.messaging().sendToDevice(data.token, payload).then(notificationResponse =>{
console.log('Successfully sent notification:', notificationResponse);
console.log('Notification Token:', data.token);
}).catch(error => {
console.log('Error sending notification 1:', error);
});
}else{
console.log('User turned off notifications');
}
}
}).catch(error => {
console.log('Error sending notification 2:', error);
})
}
我两次调用上述函数
sendNotification(userid1, payload1)
sendNotification(userid2, payload2)
功能sendNotification
完美工作。但是当我两次调用此函数时,第二次调用有时不会成功。
这种错误有哪些可能性?谢谢!
回答如下:看来您没有正确处理承诺。您可能应该将sendToDevice()返回的promise返回给sendNotification()的调用方。 sendNotification的调用者应使用返回的诺言,通过从主函数触发器返回该诺言来等待所有异步工作完成,此处未显示。
Firebase云功能有时无法正常工作
以下功能是我正在用于向用户发送通知。
function sendNotification(userID,payload){
let collectionReference = userCollection.doc(userID).collection('deviceToken').doc(documentName)
console.log('Notification userID:', userID);
console.log('Notification payload:',payload);
return collectionReference.get().then(doc => {
if (!doc.exists) {
console.log(`Notification sent failed: This user ${userID} does not have device token!`);
}else{
let data = doc.data()
console.log('User found in database....');
if(data.token !== undefined){
console.log('Token found in database....'+data.token);
admin.messaging().sendToDevice(data.token, payload).then(notificationResponse =>{
console.log('Successfully sent notification:', notificationResponse);
console.log('Notification Token:', data.token);
}).catch(error => {
console.log('Error sending notification 1:', error);
});
}else{
console.log('User turned off notifications');
}
}
}).catch(error => {
console.log('Error sending notification 2:', error);
})
}
我两次调用上述函数
sendNotification(userid1, payload1)
sendNotification(userid2, payload2)
功能sendNotification
完美工作。但是当我两次调用此函数时,第二次调用有时不会成功。
这种错误有哪些可能性?谢谢!
回答如下:看来您没有正确处理承诺。您可能应该将sendToDevice()返回的promise返回给sendNotification()的调用方。 sendNotification的调用者应使用返回的诺言,通过从主函数触发器返回该诺言来等待所有异步工作完成,此处未显示。