我正在尝试使.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))
})
})
但是我不喜欢它两次查询ref的事实。
在此示例中,我将如何获得
each
玩家的答案?什么是更正确的方法?因为我不认为这是Firebase开发人员打算这样做的方式。没有为
.on()
实施的原因是什么?因为playersSnapshot.forEach(...).then
也不是函数...每当.on('value')
触发时,如何仅执行一次操作? 最佳答案
在这里放火
我对您的问题不是很确定,因此只能回答我所能回答的部分。
没有为then()
实现[.on()
]的原因是什么?
我们在Firebase JavaScript客户端中实现了对Promises的支持。许诺的定义是,它仅解决(或失败)一次。由于Firebase on()
方法可以多次接收更新的数据,因此不符合Promise的定义。
每当.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中重现该问题吗?
关于javascript - Firebase .then与.on('value'),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44591136/