【问题标题】:Firebase database trigger - how to wait for callsFirebase 数据库触发器 - 如何等待调用
【发布时间】: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 数据库触发器)等待数据库调用完成后再继续?我有几个调用需要异步执行,并且希望不必嵌套它们来强制异步操作​​。

【问题讨论】:

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


【解决方案1】:

on() 将持久侦听器附加到将使用该位置的数据调用的查询,并且每次更改该位置的任何数据时都会再次调用该查询。该方法不返回承诺。这几乎肯定不是您想在 Cloud Functions 中做的事情。

如果您需要一次性获取数据,请使用once(),它会返回一个通过请求数据的快照解析的承诺。

【讨论】:

猜你喜欢
  • 2017-07-20
  • 2021-08-30
  • 1970-01-01
  • 2018-08-06
  • 2023-03-24
  • 2018-07-29
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
相关资源
最近更新 更多