我正在使用firebase云功能来监听数据库值事件,这是我的代码
var functions = require('firebase-functions');
var firebase = require('firebase-admin');
var serviceAccount = require("./serviceAccountKey.json");
firebase.initializeApp({
credential : firebase.credential.cert(serviceAccount),
databaseURL: "https://*******.firebaseio.com"
});
exports.notifications = functions.database.ref('/chat/{senderID}/{destinationID}/messages/{pushID}')
.onWrite(event => {
var eventSnapshot = event.data;
var sender = eventSnapshot.child('sender').val();
var message = eventSnapshot.child('message').val();
var destination = eventSnapshot.child('destination').val();
if (event.params.senderID === sender)
sendMessage(message,sender,destination);
}
);
function sendMessage(message, sender, destination) {
var senderUser = firebase.database().ref('users/'+sender+'/name');
var tokenUser = firebase.database().ref('fcm/'+destination+'/token');
tokenUser.once('value').then(function(tokenSnapshot) {
var token = tokenSnapshot.val();
console.log(token);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
onWrite函数正常执行,但tokenUser.once()
未执行。
答案 0 :(得分:0)
也许如果您尝试使用tokenUser.once('value')
并且不传递函数,并直接获取tokenSnapshot
;像这样的东西:
tokenUser.once('value').then(tokenSnapshot => {
var token = tokenSnapshot.val();
console.log(token);
});
如果您使用tokenUser.once()
进行回调,则可以传递该功能;像这样的东西:
tokenUser.once('value', function(tokenSnapshot) {
var token = tokenSnapshot.val();
console.log(token);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});