如何在带有onCreate触发器的firebase云函数中使用async/await



我已经讨论了与我的问题相关的不同主题,但无法解决它。我的带有onCreate触发器的firebasecloud函数没有部署。我得到这个错误:未能从源加载函数定义:未能从函数源生成清单:SyntaxError:await仅在异步函数和模块的顶层主体中有效

// add action to users when they have the objective already added
exports.addActionToUserWhenCreated = functions.firestore
.document('actions/{documentUid}')
.onCreate(async (snap, context) => {

// get the objectives  
let actionObjectives = snap.data().objectives
let actionId = snap.id
let objSelectedBy = []

// For each objective, get the selectedBy field
actionObjectives.forEach(objective => {
const docSnap = await db.doc(`objectives/${objective}`).get()
objSelectedBy = docSnap.data().selectedBy
objSelectedBy.forEach(user => {
// Add the actionId to the user's selectedActions
db.doc(`users/${user}/selectedActions/${actionId}`).set({
achievedRate: 0,
})
})
// Add all the userIds to the action's selectedBy field
db.doc(`actions/${actionId}`).update({
selectedBy: objSelectedBy,
}, {merge: true});
})
return;
});

你看到问题了吗?谢谢最大

解决了这个问题,但它花了我一些时间和Puff的宝贵帮助!

此处的第一个问题:forEach=>await不能在forEach中使用,但它与for。。。循环的。

第二:等待后的Promise.all=>Puff的原始答案。

因此,该功能的工作情况是:

为了便于理解,你可以用产品代替行动,用类别代替目标。这就好像你想自动向关注特定类别的每个用户添加一个新创建的产品。

exports.addActionToUserWhenCreated = functions.firestore
.document('actions/{documentUid}')
.onCreate(async (snap, context) => {
// get the objectives  
let actionObjectives = snap.data().objectives
let actionId = snap.id
let actionSelectedBy = []

// For each objective, 
for (const objective of actionObjectives) {
// get the selectedBy field (array of userIds)
const snap = await db.doc(`objectives/${objective}`).get()
const objSelectedBy = snap.data().selectedBy;
console.log("objSelectedBy",objSelectedBy)

// Add the actionId to the user's selectedActions
Promise.all(objSelectedBy.map(user => {
return db.doc(`users/${user}/selectedActions/${actionId}`).set({
achievedRate: 0,
})
}))
// Add all the objectives' userIds to the action's selectedBy field (removing duplicate):
actionSelectedBy = [...new Set([...actionSelectedBy ,...objSelectedBy])]
}
// Update the action's selectedBy field :
db.doc(`actions/${actionId}`).update({
selectedBy: actionSelectedBy,
}, {merge: true});
});

最新更新