我试图让.then()与.on()一起工作,但它只适用于.once().
我得到了playerRef.on(…).当用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))
})
})
但我不喜欢它两次查询引用的事实.
在这个例子中,我如何获得每个玩家的答案?什么是更正确的方法?因为我认为这不是Firebase开发人员想要的方式.
是什么原因导致它没有实现.on()?因为playersSnapshot.forEach(…).那么也不是函数…当.on(‘value’)触发时,我怎么只执行一次?
最佳答案
这里有一个firebaser
我不完全肯定你的问题部分,所以只回答我能做的部分.
what is the reasoning that [
then()
] is not implemented for.on()
?
我们在Firebase JavaScript客户端中实现了对Promises的支持.承诺的定义是它只解析(或失败)一次.由于Firebase on()方法可以多次接收更新的数据,因此它不适用于promise的定义.
How do I execute something only once whenever the
.on('value')
triggers?
如果只想对事件响应一次,则应使用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中重现这个问题吗?
相关文章