【发布时间】:2019-08-17 20:32:06
【问题描述】:
我无法在 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 数据库触发器)等待数据库调用完成后再继续?我有几个调用需要异步执行,并且希望不必嵌套它们来强制异步操作。
【问题讨论】:
-
尝试使用返回承诺的
.once()而不是.on()。 -
如果您开始使用 Cloud Functions 和实时数据库,您可能需要从一些视频教程开始。 firebase.google.com/docs/functions/video-series
标签: javascript firebase firebase-realtime-database google-cloud-functions