我的 firebase 看起来像这样:
这是测试代码( CoffeeScript ):
Firebase = require 'firebase'
ref = new Firebase 'https://my_firebase.firebaseio.com/items'
ref.once 'child_added', (snapshot) ->
childRef = snapshot.ref()
console.log "child_added", childRef.toString(), snapshot.val()
childRef.transaction(
(data) ->
console.log 'transaction on data', data
return if !data or data.my_key isnt 'my_val'
data.my_key = 'new_val'
return data
,
(err, commited, snapshot) ->
if err
console.error 'error', err
return
console.log 'commited? '+commited
console.log 'server data', snapshot.val()
,
false
)
并输出:
child_added https://my_firebase.firebaseio.com/items/item1 { my_key: 'my_val' }
transaction on data null
commited? false
server data null
当 transaction(...)
的第三个参数为 true 时,也会发生同样的情况。
为了使此代码正常工作,我必须将 ref.once 'child_added', (snapshot) ->
更改为 ref.on 'child_added', (snapshot) ->
( 一次
到on
)。更改后输出为:
child_added https://my_firebase.firebaseio.com/items/item1 { my_key: 'my_val' }
transaction on data { my_key: 'my_val' }
commited? true
server data { my_key: 'new_val' }
似乎由于某种原因,当我使用once
时,数据未正确同步,本地快照未更新,并且事务“认为”引用下没有数据。这是一个错误还是我做错了什么?我知道 updateFunction
可以被多次调用的事务,以及第三个参数(我已经尝试过 true 和 false 选项),但我仍然无法理解为什么事务在使用时不起作用一次
获得一个 child 。
最佳答案
事务最终应该成功,并在正确的数据状态上运行,但最初将在“未缓存”状态下运行,这意味着它将针对客户端的本地数据副本运行(可能是 null
) ,尝试将更改提交到服务器(这将失败),然后重试事务。
这是正常,并且是预期的。但是,如果交易从未成功,我建议您联系支持人员:[email protected]继续解决问题。
关于firebase - Firebase事务的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27169516/