Firebase Then with.on ('value')

I am trying to get .then()to work with .on(), but it only works with .once().

I get playersRef.on(...).then is not a functionwhen I try usingon()

So, I have the following:

   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))
      })
    })

But I do not like the fact that he requests a link twice.

How can I get the player response eachin this example? What would be the more correct way? Because I don’t think it was as the Firebase developers planned.

And what is the argument that it is not implemented for .on()? Since it is playersSnapshot.forEach(...).thenalso not a function ... How do I execute something only once when the triggers .on('value')?

+5
1

firebaser

, , .

, [ then()] .on()?

Promises Firebase JavaScript. , ( ) . 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?

+7

All Articles