实时数据库事务中如何处理空值?

How to deal with null value in realtime database transaction?

我想要一个可以使用事务递增或递减的计数器。我不想将计数器初始化为 0,而是它在开始时不存在。所以我会写增量交易如下

ref.transaction(function(counterValue){
    if (counterValue == null) return 1
    else return (counterValue +1)
},function(error,committed,snapshot){
   if (error){//fail
   }else if (!committed){//aborted
   }else{//successfull
   }
})

但我不确定交易是否会 运行 正确,因为 counterValue 的 null 值可能意味着没有现有节点,而且当本地缓存为空时。 谁能告诉我应该怎么做?

the null value of counterValue could mean no existing node but also when local cache is empty

如果因为本地缓存不包含当前值而将现有值报告为 null,则您 return 的新值并不重要,因为您的处理程序无论如何都会重新运行.

所以你的处理程序对我来说很好,虽然我通常将其缩短为:

return (counterValue || 0) + 1