事务以 Amazon SimpleDB 或数据库分片集群的方式工作。也就是说,它们是“最终一致”而不是保证一致。
因此,当您使用事务时,处理函数可能会使用本地值(在某些情况下,如果从未检索到则为 null)多次调用,然后使用同步值(无论服务器上有什么)再次调用。
Example:
pathRef.transaction(function(curValue) {
// this part is eventually consistent and may be called several times
}, function(error, committed, ss) {
// this part is guaranteed consistent and will match the final value set
});
这确实是你处理交易时必须秉持的心态。您应该始终预期会有多个调用,因为第一个事务可能会与另一个更改发生冲突并被拒绝。您不能使用事务的处理方法来获取服务器值(尽管您可以从成功回调中读取它)。
防止本地触发事件
当事务发生时,在到达服务器之前会触发本地事件以进行延迟补偿。如果事务失败,则本地事件将被恢复(触发更改或删除事件)。
您可以使用applyLocally
财产关于交易 https://www.firebase.com/docs/javascript/firebase/transaction.html覆盖此行为,这会使本地结果变慢,但确保仅在本地触发服务器值。
pathRef.transaction(function(curValue) {
// this is still called multiple times
}, function(error, committed, ss) {
// this part is guaranteed consistent and will match the final value set
},
// by providing a third argument of `true`, no local event
// is generated with the locally cached value.
true);