Firebase数据库触发器-如何等待调用 [英] Firebase database trigger - how to wait for calls
问题描述
我无法在firebase数据库函数中进行异步操作.
I am having trouble making asynchronous operations in firebase database functions.
我尝试了下面的代码
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数据库触发器)等待数据库调用完成后再继续?我有几个需要异步执行的调用,希望不必嵌套它们以强制执行异步操作.
How can I make Google Cloud Functions (Firebase database trigger) to wait for the database call to finish before proceeding? I have several calls that needs to be executed asynchronously and wish not to have to nest them to force asynchronous operation.
推荐答案
on() attaches a persistent listener to a query that will get invoked with the data at that location, and again for each change to any data at that location. The method does not return a promise. This is almost certainly never what you want to do in Cloud Functions.
Instead, if you need to get data a single time, use once(), which returns a promise that resolves with a snapshot of the requested data.
这篇关于Firebase数据库触发器-如何等待调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!