【问题标题】:How to distinguish between the reasons Firebase Transactions return null?如何区分 Firebase Transactions 返回 null 的原因?
【发布时间】:2020-05-27 03:29:51
【问题描述】:

根据我对Transactions的理解,它可以返回null有两个原因:

  1. 在执行事务的节点上实际上没有任何值。
  2. 本地缓存为空,因为 Firebase Cloud Functions 是无状态的。因此,它可能会在第一次返回null 并重新运行该函数。

我的问题是,我们如何区分这两种情况?还是 firebase 自己做区分?

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,当它第一次尝试获取数据时执行交易。

如果Myref 的值实际上是空的,我希望在此处填写数字1238484。如果不是,并且null实际上是由于事务读取错误而被抛出,我该如何区分?

PS:请不要在节点上建议监听器。还有其他更有效的方法吗?

【问题讨论】:

  • 您试图通过交易解决的具体问题是什么?
  • 这是为了更好地理解交易。我现在已经简化了这个例子。使用我编写的代码,如果节点上没有值,我希望事务中止。但问题是,由于交易本身的性质,即使节点上有值,它也会被中止。
  • 您是否正在验证 node.exists() 返回 true,因为这将帮助您确定节点是否存在,因此您不会在空位置调用它。
  • 在我的 PS 中,除了检查 node.exists() 之外,我还要求提供其他方法。

标签: firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

事务初始运行时,更新函数返回的值为undefinedonComplete is invoked with error to be null

对于没有数据时的后续运行,a reason for aborting the transaction is provided

可以通过查看error的值来区分是引用处没有数据还是本地缓存为空。

error === null && !committed // local cache is empty
error !== null && !committed // there is no data

这是内部实现细节,您不应依赖它进行查询。

【讨论】:

  • 那么,如果数据库 ref 中确实有数据,但它在第一次运行时仍然返回 null,如你所说,你会怎么做?,我该如何克服这个问题?我从交易中收到 null 但它不应该返回 null 我认为它正在发生是因为你提到的本地缓存的事情
猜你喜欢
  • 1970-01-01
  • 2020-09-18
  • 2021-12-09
  • 2023-03-10
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
相关资源
最近更新 更多