【发布时间】:2019-06-02 14:35:32
【问题描述】:
我正在尝试使用 Firebase 函数做一个相对简单的理论上的函数。
具体来说:
-
将
+ 1添加到所有用户的实时数据库变量中 -
向所有用户发送通知
我仍在努力理解async/await,这可能是我为此苦苦挣扎的原因。
这是我正在做的事情:
exports.gcIncrement = functions.database
.ref('gthreads/{threadId}/messages/{messageId}')
.onCreate(async (snapshot, context) => {
const data = snapshot.val();
const threadId = context.params.threadId;
const uid = context.auth.uid;
adb.ref('gchats/' + threadId).once('value').then(async (gchatData) => {
const parent = gchatData.val();
incrementUser(parent.users, uid, threadId); //parent.users is an object with 1-30 users.
sendGCNotification(parent.users, data);
return true;
}).catch(error => console.log(error))
});
然后我有函数incrementUser:
function IncrementUser(array, uid, threadId) {
for (const key in array) {
if (key != uid) {
const gcMessageRef =
adb.ref('users/' + key + '/gthreads/' + threadId + '/' + threadId+'/unread/');
gcMessageRef.transaction((int) => {
return (int || 0) + 1;
}
}
}
和函数sendGCNotification:
function sendGCNotification(array, numbOfMsg, data) {
let payload = {
notification: {
title: 'My App - ' + data.title,
body: "This is a new notification!",
}
}
const db = admin.firestore()
for (const key in array) {
if (!data.adminMessage) {
if (array[key] === 0) {
const devicesRef = db.collection('devices').where('userId', '==', key)
const devices = await devicesRef.get();
devices.forEach(result => {
const tokens = [];
const token = result.data().token;
tokens.push(token)
return admin.messaging().sendToDevice(tokens, payload)
})
}
}
}
}
我目前收到错误:
'await' 表达式只允许在异步函数中使用。
const devices = await devicesRef.get();
但即使我得到它没有错误,它似乎也不起作用。 Firebase 函数日志说:
下午 4:45:26.207 gc增量 函数执行耗时 444 毫秒,完成状态为:'ok' 下午 4:45:25.763 gc增量 函数执行开始
所以它似乎按预期运行,但没有按预期完成代码。有任何想法吗?谢谢!
【问题讨论】:
标签: javascript firebase google-cloud-functions