并非所有代码路径都会返回多批写入Google Firestore云函数Typescript的值 上下文
我已经编写了一些能够正确执行批处理写入的云函数。在这个实例中,由于数据库模式,我必须搜索与userA uid或userB uid字段匹配的文档 模式/功能 这个模式不是最聪明的,如果有更干净的解决方案,请告诉我。它用于应用程序的消息传递方面。其中,每个文档都有一组userA和userB字段 当用户更改其用户名并且必须更新“对话”集合中包含用户数据的文档时,会触发此功能 我必须执行两个单独的查询,因为我正在搜索两个不同的文档字段,其中可能包含需要更新其信息的用户的id 批写操作使用用户为userA或其为userB的实例的新信息更新文档 问题 我认为,通过为每个查询创建两个单独的批处理写入并正确返回它们,它将“返回所有代码路径”,然而tsLint告诉我的是不同的 我试过的 即使当我试图解释此处所述的不存在的已发送文档时: 我仍然没有正确返回所有代码路径 例如:并非所有代码路径都会返回多批写入Google Firestore云函数Typescript的值 上下文,typescript,google-cloud-firestore,google-cloud-functions,Typescript,Google Cloud Firestore,Google Cloud Functions,我已经编写了一些能够正确执行批处理写入的云函数。在这个实例中,由于数据库模式,我必须搜索与userA uid或userB uid字段匹配的文档 模式/功能 这个模式不是最聪明的,如果有更干净的解决方案,请告诉我。它用于应用程序的消息传递方面。其中,每个文档都有一组userA和userB字段 当用户更改其用户名并且必须更新“对话”集合中包含用户数据的文档时,会触发此功能 我必须执行两个单独的查询,因为我正在搜索两个不同的文档字段,其中可能包含需要更新其信息的用户的id 批写操作使用用户为userA
//Changed from this
const batch = db.batch()
querySnapshot.forEach(doc => {
batch.update(doc.ref, {
profileImageURL: newProfilePic
})
})
return batch.commit()
//To this
const batch = db.batch()
querySnapshot.forEach(doc => {
if (!doc.exists) {
console.log("Document does not exists: " + doc.data())
} else {
batch.update(doc.ref, {
userAusername: newUsername
})
}
})
return batch.commit()
这是完整的函数
export const updateUserUsernameInConversations = functions.firestore
.document('users/{userId}')
.onUpdate(async (change, context) => {
const { userId } = context.params
const newUsername = change.after.data().username
const oldUsername = change.before.data().username
if (newUsername !== oldUsername) {
const conversationsRef = db.collection('Conversations')
const conversationQueryA = conversationsRef.where('userAuid', '==', userId)
const conversationQueryB = conversationsRef.where('userBuid', '==', userId)
conversationQueryA.get()
.then(querySnapshot => {
if (querySnapshot.empty) {
return null
} else {
const batch = db.batch()
querySnapshot.forEach(doc => {
batch.update(doc.ref, {
userAusername: newUsername
})
})
return batch.commit()
}
})
conversationQueryB.get()
.then(querySnapshot => {
if (querySnapshot.empty) {
return null
} else {
const batch = db.batch()
querySnapshot.forEach(doc => {
batch.update(doc.ref, {
userBusername: newUsername
})
})
return batch.commit()
}
})
} else {
return null
}
})
问题不在于批次。问题在于,您的大型云函数代码没有返回在所有异步工作完成时解决的承诺()。事实上,对于主
if(newUsername!==oldUsername)
块,代码根本不返回任何内容,这是一个问题
至少,您的代码应该更像这样:
if (newUsername !== oldUsername) {
// ...
const promiseA = conversationQueryA.get()
// ...
const promiseB = conversationQueryB.get()
// ...
return Promise.all([promiseA, promiseB])
}
else {
return null
}
现在,无论采用哪个主代码路径,它都将返回一个值,并且它将返回一个承诺,该承诺只有在两个异步工作链完成后才能解析