Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何区分Firebase事务返回null的原因?_Firebase_Firebase Realtime Database_Google Cloud Functions - Fatal编程技术网

如何区分Firebase事务返回null的原因?

如何区分Firebase事务返回null的原因?,firebase,firebase-realtime-database,google-cloud-functions,Firebase,Firebase Realtime Database,Google Cloud Functions,根据我对事务的理解,它可以返回null,原因有二: 在执行事务的节点上实际上没有值 本地缓存为空,因为Firebase云函数是无状态的。因此,它可能会在第一次返回null,并重新运行该函数 我的问题是,我们如何区分这两种情况?还是firebase本身就有区别 Myref.transaction(function(currentData) { if(currentData != null) { return currentData + 1; } else {

根据我对事务的理解,它可以返回
null
,原因有二:

  • 在执行事务的节点上实际上没有值
  • 本地缓存为空,因为Firebase云函数是无状态的。因此,它可能会在第一次返回
    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
    当它在执行事务时第一次尝试获取数据时,事务回调将传递
    null

    如果
    Myref
    的值实际上是空的,我希望在那里填入数字
    1238484
    。如果不是,并且由于事务的错误读取而实际抛出了
    null
    ,我如何进行区分


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

    在事务初始运行时,更新函数返回的值是未定义的

    对于没有数据时的后续运行

    您可以检查error的值,以区分引用中是否没有数据,或者本地缓存是否为空

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

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

    您试图通过事务解决的具体问题是什么?这是为了更好地理解事务。我现在简化了这个例子。使用我编写的代码,如果节点上没有值,我希望事务中止。但问题是,由于事务本身的性质,即使节点上有值,它也会被中止。您是否验证该节点。exists()返回true,因为这将帮助您确定该节点是否存在,因此您不会在空位置调用它。在我的PS中,我要求提供一种方法,而不是检查node.exists()是否存在。那么,如果数据库ref中确实有数据,但它在第一次运行时仍返回null,您会怎么做?我如何克服这个问题?我从Transaction接收null,但它不应该返回null,我假设这是因为您提到的本地缓存