Reputation: 3417
I am having trouble making asynchronous operations in firebase database functions.
I have tried the code below
exports.onTodoCreate = functions
.region('europe-west1')
.database
.ref('/todos/{userId}/{todoId}')
.onCreate( async (snapshot, context) => {
console.log('Begin')
//Collect email address
const email = '[email protected]'
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)
The expected output is:
Begin
otherUserExists-1 true
otherUserExists-2 true
What I see in the logs is:
Begin
otherUserExists-2 false
otherUserExists-1 true
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.
Upvotes: 1
Views: 733
Reputation: 317828
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.
Upvotes: 3