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

Blo*_*nge 6 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))
      })
    })
Run Code Online (Sandbox Code Playgroud)

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

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

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

Fra*_*len 8

这里有一个firebaser

我不完全肯定你问题的一部分,所以只会回答我能做的部分.

是什么原因导致[ 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()
      }
   })
})
Run Code Online (Sandbox Code Playgroud)

如果你在完成这项工作时遇到问题,你可以在jsbin中重现这个问题吗?