如何区分Firebase Transactions返回null的原因? [英] How to distinguish between the reasons Firebase Transactions return null?
问题描述
据我对交易的理解,它可以返回 null
,原因有两个:
From my understanding of Transactions, it can return null
for two reasons:
- 正在执行事务的节点上实际上没有任何值.
- 由于Firebase Cloud Functions是无状态的,因此本地缓存为空.因此,它可能会在第一次返回
null
并将重新运行该函数.
- There is actually no value at the node where the transaction is being performed.
- The local cache is empty as Firebase Cloud Functions is stateless. Therefore, it may return
null
the very first time and it will re-run the function.
我的问题是,我们如何区分这两种情况?还是firebase自己做区分?
My question is, how do we distinguish between these two cases? Or does firebase do the distinction by itself?
Myref.transaction(function(currentData) {
if(currentData != null) {
return currentData + 1;
} else {
console.log("Got null")
return;
}
}, function(error, committed, snapshot) {
if(!committed) {
// The transaction returned null.
// But don't know if it's because the node is null or
// because the transaction failed during the first iteration.
}
});
在上面的示例中,当 Myref
上的值不存在时和 时,事务回调都将传递 null
在执行事务时的第一次尝试中获取数据.
In the above example, the transaction callback will be passed null
both when the value at Myref
is non-existent and when it attempts to get the data in the very first try when executing the transaction.
如果 Myref
的值实际上为空,我希望在其中填写数字 1238484
.如果不是,并且由于事务读取错误而实际上抛出了 null
,我该如何区分?
If the value of Myref
is actually empty, I want the number 1238484
to be filled in there. If it is not, and the null
is actually being thrown because of a wrong read by the transaction, how do I make this distinction?
PS:请不要在该节点上建议听众.还有其他更有效的方法吗?
PS: Please don't suggest a listener at the node. Is there any other more effective way of doing this?
推荐答案
在事务的初始运行中,从更新函数返回的值是 undefined
,
On initial run of the transaction and value returned from the update function is undefined
, onComplete
is invoked with error to be null
For subsequent runs when there is no data, a reason for aborting the transaction is provided.
您可以检查error的值以区分参考处没有数据还是本地缓存为空.
You can check the value of error to differentiate whether there is no data at the reference or local cache is empty.
error === null && !committed // local cache is empty
error !== null && !committed // there is no data
这是内部实现的详细信息,您不应依赖它进行查询.
This is internal implementation detail and you shouldn't rely on it for your queries.
这篇关于如何区分Firebase Transactions返回null的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!