因此,今天我更新了firebase cli,然后部署了新功能。尽管Firebase日志显示通知已发送到这么多令牌,但不会发生通知。日志中显示错误
函数返回了未定义的预期承诺或值
我在堆栈溢出中搜索答案,但没有任何帮助。 我也想补充一点,在它显示出其他错误之前
TypeError:无法读取null的属性“描述”
现在突然显示函数未定义返回。
不确定什么是错误的。任何帮助表示赞赏。
Index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
function token_send(admin,title_input,body_input,getBody,getDeviceTokensPromise,change){
// Only edit data when it is first created.
if (change.before.val()) {
return 0;
}
// Exit when the data is deleted.
if (!change.after.val()) {
return 0;
}
return Promise.all([getDeviceTokensPromise,getBody]).then(results => {
const tokensSnapshot = results[0];
const notify=results[1];
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
var contentAlert = change.after.val();
// Notification details.
const payload = {
'data': {
'title': title_input,
'body': body_input
}
};
const tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
console.log("Successfully sent message:", response);
console.log("content alert",contentAlert);
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
// Cleanup the tokens who are not registered anymore.
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);
});
});
}
exports.sendNotificationCouncil = functions.database.ref(`path/Post/{pushId}`).onWrite((change,context) => {
const getDeviceTokensPromise = admin.database().ref(`/Token/token_no`).once('value');
const getBody=admin.database().ref(`/Post`).once('value');
var title_input='You have new Post';
var contentAlert = change.after.val();
var body_input=contentAlert.description; //showing error here
token_send(admin,title_input,body_input,getBody,getDeviceTokensPromise,change);
});
答案 0 :(得分:0)
您应该在token_send()
Cloud Function中返回承诺(由sendNotificationCouncil
返回),如下所示:
exports.sendNotificationCouncil = functions.database.ref(`path/Post/{pushId}`).onWrite((change,context) => {
const getDeviceTokensPromise = admin.database().ref(`/Token/token_no`).once('value');
const getBody=admin.database().ref(`/Post`).once('value');
var title_input='You have new Post';
var contentAlert = change.after.val();
var body_input=contentAlert.description; //showing error here
return token_send(admin,title_input,body_input,getBody,getDeviceTokensPromise,change);
});
请注意,这也是捕获函数中错误的最佳实践,在这种情况下,返回false
。