Firebase数据库触发器-如何等待调用 [英] Firebase database trigger - how to wait for calls

查看:84
本文介绍了Firebase数据库触发器-如何等待调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆