How to distinguish between the reasons Firebase Transactions return null?

僤鯓⒐⒋嵵緔 提交于 2021-02-18 15:01:13

问题


From my understanding of Transactions, it can return null for two reasons:

  1. There is actually no value at the node where the transaction is being performed.
  2. 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.

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.
    }
});

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.

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: Please don't suggest a listener at the node. Is there any other more effective way of doing this?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/60173683/how-to-distinguish-between-the-reasons-firebase-transactions-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!