我试图从作者那里获取值,但它说它是未定义的。
如何在 Cloud Functions for Firebase 的 javascript 中从 firebase 中获取特定子项的值,下面的代码应该可以工作(?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPushForHelp =
functions.database.ref('/schools/Vittra/alarms/active/{id}').onCreate(event => {
const id = event.params.id;
var eventSnapshot = event.data.val();
var ref = admin.database().ref("/schools/Vittra/alarms/{eventSnapshot}/authorId");
ref.once('value').then(function(snapshot) {
var author = snapshot.val();
});
const payLoad = {
notification: {
title: String(eventSnapshot),
body: String(author),
badge: '1',
sound: 'Intruder.mp3'
}
};
return admin.database().ref('fcmToken').once('value').then(allToken => {
if (allToken.val()) {
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payLoad).then(response =>
{
});
};
});
});
您忽略了此查询返回的承诺:
ref.once('value').then(function(snapshot) {
var author = snapshot.val();
});
在使用author
的值之前,您需要 但是依赖于响应该承诺的函数内部author
的代码,更像这样:
var author;
return ref.once('value').then(function(snapshot) {
author = snapshot.val();
return admin.database().ref('fcmToken').once('value')
}).then(function(snapshot) {
if (allToken.val()) {
const token = Object.keys(allToken.val());
const payLoad = ...
return admin.messaging().sendToDevice(token, payLoad)
}
}).then(function(response) {
// ...continue
})
最重要的是,您需要学习如何正确链接您的承诺。
您已在 Firebase 回调中声明了作者。
var eventSnapshot = event.data.val();
var ref = admin.database().ref("/schools/Vittra/alarms/{eventSnapshot}/authorId");
ref.once('value').then(function(snapshot) {
var author = snapshot.val(); // Here is the problem
});
您在这里将其用作:
const payLoad = {
notification: {
title: String(eventSnapshot),
body: String(author), // <------
badge: '1',
sound: 'Intruder.mp3'
}
};
在外面定义作者,如 eventSnapshot ,然后你可以进一步使用它。
用:
var eventSnapshot = event.data.val();
var author = '';
var ref = admin.database().ref("/schools/Vittra/alarms/{eventSnapshot}/authorId");
ref.once('value').then(function(snapshot) {
author = snapshot.val();
});