Firebase。然后使用.on('value')

时间:2016-11-03 12:57:46

标签: javascript firebase firebase-realtime-database

我正在尝试.then()使用.on(),但它仅适用于.once()

在使用playersRef.on(...).then is not a function

进行尝试时,我得到on()

所以我现在拥有的是:

   let nodesRef = Firebase.database().ref('players')
   let answers = {}
   playersRef.on('value', (playersSnapshot) => {
      playersRef.once('value').then((playersSnapshot) => {
        playersSnapshot.forEach((playerSnapshot) => {
          let playerKey = playerSnapshot.key
          let answersRef = playerSnapshot.child('answers')
          if (answersRef .exists()){
            answers[playerKey ] = answersRef .val()
          }
        })
      }).then(() => {
        console.info(answers);
        dispatch(setPlayerAnswers(answers))
      })
    })

但我不喜欢它两次查询引用的事实。

在这个例子中,我如何获得each玩家的回答?什么是更强正确方式?因为我认为这不是Firebase开发人员想要的方式。

是什么原因导致.on()没有实现?因为playersSnapshot.forEach(...).then也不是一个函数......每当.on('value')触发时,如何执行一次

1 个答案:

答案 0 :(得分:8)

firebaser here

我不是你问题的全部内容,所以只回答我能做的部分。

  

then()没有实现[.on()]的原因是什么?

我们在Firebase JavaScript客户端中实现了对Promise的支持。承诺的定义是它只解析(或失败)一次。由于Firebase on()方法可以多次接收更新的数据,因此它不适用于承诺的定义。

  

每当.on('value')触发时,我如何只执行一次?

如果您只想对事件做出一次回复,则应使用once()方法。

我不确定你为什么会遇到forEach()的问题。以下应该有效:

playersRef.on('value', (playersSnapshot) => {
   playersSnapshot.forEach((playerSnapshot) => {
      let playerKey = playerSnapshot.key
      let answersRef = playerSnapshot.child('answers')
      if (answersRef .exists()){
        answers[playerKey ] = answersRef .val()
      }
   })
})

如果您在执行此操作时遇到问题,可以在jsbin中重现该问题吗?