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

时间:2019-08-17 20:32:06

标签: 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数据库触发器)在完成数据库调用之前等待?我有几个需要异步执行的调用,并且希望不必嵌套它们以强制执行异步操作。

1 个答案:

答案 0 :(得分:3)

on()将持久性侦听器附加到查询,该查询将使用该位置的数据进行调用,并再次对该位置上的任何数据进行更改。该方法不返回承诺。几乎可以肯定,这绝不是您在Cloud Functions中要做的。

相反,如果您需要一次获取数据,请使用once(),它返回一个可以解决所请求数据快照的承诺。