我试图用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 Functions日志显示:
4:45:26.207 PM gcIncrement函数执行时间为444 ms,已完成,状态为“OK”4:45:25.763 PM gcIncrement函数执行开始
所以它看起来像预期的那样运行,但没有像预期的那样实现代码。有什么想法吗?谢谢!
await
的所有用法都必须发生在标记为async
的函数主体中。您的函数sendgcnotification
不是异步的。您必须将其标记为异步,并且还要确保它中的任何承诺都是等待的,或者返回一个承诺,当所有异步工作完成时,该承诺就会解析。
此外,在incrementuser
中,您没有处理GCMessageRef.transaction()返回的承诺。您需要处理从所有异步工作中生成的每个承诺,并确保它们都是从顶级函数返回或等待的最终承诺的一部分。
如果您想了解更多关于Cloud函数代码中的promises和Async/Await的信息,我建议您使用我的视频系列。具体地说,一篇题为“Async/Await如何与TypeScript和ECMAScript 2017一起工作?”的文章。即使不使用TypeScript,async/await也以同样的方式工作。