我在firebase项目中实现了下面的函数,并将其部署到我的云函数中,但在执行时,它会导致firebase控制台的函数日志中出现错误;
> TypeError: Cannot read property 'profileImgUrl' of undefined
我理解它产生的错误的含义,但我不明白为什么我的用户变量会是未定义的
以下是功能:
exports.eventInvites = functions.firestore
.document('Events/{eventId}').onCreate((snap, context) => {
const eventData = snap.data();
const eventId = context.params.eventId;
const invitees = eventData.invitees;
let user;
db.doc(`Users/${eventData.createdBy}`).get().then(doc => {
var data = doc.data();
user = data; // updated user data but still get undefined
return user;
}).catch(error => {
console.log(error.message);
});
if (invitees !== undefined || invitees.length > 0) {
invitees.forEach(invitee => {
db.collection('Users').doc(invitee).collection('feed').doc().set({
date: new Date(),
image: user.profileImgUrl, // error occurs here, says user is undefined
summary: `${user.firstName} ${user.lastName} invited you to an event`,
extraText: `${eventData.eventName}: ${eventData.eventDetails} `,
extraImages: [
eventData.eventImgUrl
]
}).catch(error => {
console.log(error.message)
});
});
}
});
get()
是异步的,因此它之后的代码在之前执行。为了解决这个问题,您可以将所有代码放入get()
:中
db.doc(`Users/${eventData.createdBy}`).get().then(doc => {
var data = doc.data();
user = data;
if (invitees !== undefined || invitees.length > 0) {
invitees.forEach(invitee => {
db.collection('Users').doc(invitee).collection('feed').doc().set({
date: new Date(),
image: user.profileImgUrl,
summary: `${user.firstName} ${user.lastName} invited you to an event`,
extraText: `${eventData.eventName}: ${eventData.eventDetails} `,
extraImages: [
eventData.eventImgUrl
]
})
});
}
return user;
}).catch(error => {
console.log(error.message);
});