我在 firebase 数据库函数中进行异步操作时遇到问题。
我试过下面的代码
exports.onTodoCreate = functions
.region('europe-west1')
.database
.ref('/todos/{userId}/{todoId}')
.onCreate( async (snapshot, context) => {
console.log('Begin')
//Collect email address
const email = 'test@somewhere.com'
let otherUser = {}
let otherUserExists = false
await snapshot.ref.root.child('users')
.orderByChild('email')
.equalTo(email)
.on('value', (userSnapshot) => {
userSnapshot.forEach((data) => {
//Collect data
otherUser = {
...data.val()
}
otherUser .id = data.key
otherUserExists = true
console.log('otherUserExists-1', otherUserExists)
})
})
console.log('otherUserExists-2', otherUserExists)
预期的输出是:
Begin
otherUserExists-1 true
otherUserExists-2 true
我在日志中看到的是:
Begin
otherUserExists-2 false
otherUserExists-1 true
如何让 Google Cloud Functions(Firebase 数据库触发器)在继续之前等待数据库调用完成?我有几个需要异步执行的调用,我希望不必嵌套它们来强制异步操作。
最佳答案
on()将持久性监听器附加到将使用该位置的数据调用的查询,并再次针对该位置的任何数据进行每次更改。该方法不返回 promise 。这几乎肯定不是您想要在 Cloud Functions 中执行的操作。
相反,如果您需要一次获取数据,请使用 once() ,它返回一个使用所请求数据的快照解析的 promise 。
关于javascript - Firebase 数据库触发器 - 如何等待调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57539746/