javascript - Firebase 数据库触发器 - 如何等待调用

标签 javascript firebase firebase-realtime-database google-cloud-functions

我在 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/

相关文章:

Firebase 安全规则 : compare two objects for equality?

javascript - 退出父函数的函数

javascript - 带有图例和其他颜色的 Google Charts API 散点图

java - 是否有Java或任何api可以通过给定的字符串(例如Apple-> Fruit)检测产品类型(类别)?

firebase - 如何保持 Firebase 登录?

android - Firebase 相当于 MySQL 的 NOW()?

javascript - 当用户单击“保存”时,如何使用输入字段将图像转换为 Base64

javascript - 如何在 webkit 浏览器中访问粘贴的文件? (如谷歌浏览器)

javascript - TypeError : _app2. default.database 不是函数。 (在 '_app2.default.database()' 中, '_app2.default.database' 未定义)

java - 如何从 ValueEventListener Firebase 检索数据