Firebase实时数据库事务处理程序大多数时候被调用两次 [英] Firebase realtime database transaction handler gets called twice most of the time
问题描述
我正在使用事务在Node.js应用中使用Firebase管理API写入Firebase实时数据库中的特定位置.我观察到,即使没有其他客户端使用数据库,事务处理程序也会被调用两次.
I am using transactions to write to a specific location in firebase realtime database with firebase admin api in my nodejs app. I observed that the transaction handler gets called twice, even when there are no other clients using the database.
以下是显示此行为的最少代码.
Following is a minimal code which displays this behavior.
firebaseAdmin.database().ref('some/path').transaction(currentData => {
console.log('transaction handler got called');
return {'abc': 'def'};
}, null, false).then(value => {
console.log('transaction complete')
}).catch(reason => {
console.log('transaction failed. ' + reason);
});
我可以观察到,每次执行上述代码,transaction handler got called
都会被记录两次.
I can observe that transaction handler got called
gets logged twice for each execution of above code.
我了解,如果读取其他currentData
窗口中的db路径中的其他客户端写入事务,并且尝试将新数据提交到db路径,则可以多次调用该处理程序.但是,在我的情况下,没有其他客户端,因此我无法理解为什么需要两次调用事务处理程序.
I understand that the handler can get called multiple times if some other client writes to the db path in the window between currentData
is read for a transaction and the new data is attempted to be committed to the db path. But, there are no other clients in my case, so I cannot understand why the transaction handler needs to get called twice.
有人知道这是什么原因吗?
Does anyone know what is the reason for this?
推荐答案
这是预期的行为.当您运行事务时,Firebase客户端会以其对当前值some/path
的最佳猜测立即调用您的事务处理程序.第一次运行它时,最好的猜测通常是null
.如果some/path
已经存在,那总是错误的,并且一旦客户端具有正确的当前值,将始终导致对事务处理程序的第二次调用.
This is expected behavior. When you run a transaction, the Firebase client immediately calls your transaction handler with its best guess of the current value of some/path
. The first time you run it, this best guess is typically null
. If some/path
already exists that is always wrong, and will always lead to a second call to your transaction handler once the client has the correct current value.
在流程图中看起来像这样
In a flow chart it looks something like this
app code client server
+ +
transaction() | |
|+--+ |
| |current == null |
| v |
| |new = 0 |
|<--+ |
| |
| current==null, new=0 |
|+----------------------->|
| |+--+
| | |current != null
| | v
| | |current = 0
| |<--+
| NACK, current=0 |
|<-----------------------+|
| |
|+--+ |
| |curent==0 |
| v |
| |new=1 |
|<--+ |
| |
| current==0, new=1 |
|+----------------------->|
| |+--+
| | |current == 0
| | v
| | |current = 1
| |<--+
| ACK, current=1 |
|<-----------------------+|
| |
+ +
另请参阅以下有关交易方式的说明:
Also see these explanations of how transactions work:
- Firebase runTransaction not working - MutableData is null
- Strange behaviour of firebase transaction
- Android Firebase database transaction
这篇关于Firebase实时数据库事务处理程序大多数时候被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!