1

我的云功能,像这样:火力点云功能的交易工作零星

exports.updateNewsCount = functions.database.ref('/channels/{channelId}/news/{newsId}/') 
.onWrite (event => { 
    const channelId = event.params.channelId; 
    const newsId = event.params.newsId; 
    let CntRef = admin.database().ref('/channelDetails/' + channelId + '/newsCnt'); 
    if (event.data.exists() && !event.data.previous.exists()){ 
     return CntRef.transaction(function(current){ 
      if (current){ 
       console.log ('current is not null'); 
       return (current || 0) + 1; 
      } 
      else { 
       console.log('current is null'); 
       return current; 
      } 
     },function(error, b, d){ 
      if (error) 
       console.log(error); 
      else 
       console.log ('error is null'); 
      if (b) 
       console.log('boolean is true'); 
      else 
       console.log('boolean is false'); 

      if (d) 
       console.log('snapshot is ' + d); 
      else 
       console.log ('snapshot is null'); 
     }).then(()=>{}); 
    } else if (!event.data.exists() && event.data.previous.exists()){ 
     return CntRef.transaction(function(current){ 
      if (current) 
       return (current || 1) - 1; 
      else 
       return current; 
     }, function(error, b, d){if (error) console.log(error); if (d) console.log(d);}).then(()=>{}); 
    } 
}); 

它触发持续,我可以看到日志条目。但是,newsCnt字段未按预期更新。有时它会被更新,有时候不会!我在这里做错了什么?

+0

您是否曾尝试在您希望执行事务的各个点上进行登录,以查看它实际上在执行的操作? –

+0

是的。在多个地方添加了console.log,并且在工作时,日志如预期。云功能也总是以状态正常返回。所以我知道没有语法错误。 –

+0

每次需要时都会正确触发云端功能。该函数根据日志以状态ok返回。当它工作时,(我的console.logs在上面的代码中被剥离了)告诉我事务被尝试了两次,一次是当前为空,而另一次当前时间不为空。我有一种感觉,也许还有其他的云功能会阻止它完成或者类似的事情。 –

回答

1

您应该期望可能多次调用一个事务,第一次使用null。这就是交易的方式。请阅读文档here

特别注意到该节中的下列标注:

注:由于您的更新函数被调用多次,它必须 能够处理空数据。即使您的 远程数据库中存在现有数据,但在运行事务 函数时可能不会在本地进行缓存,导致初始值为空。

+0

是的,我已经理解了。我想我的代码也照顾到了这一点。当电流为空时,我正在返回电流。 –

+0

如果您为事务的onComplete参数提供一个函数并记录其参数,您会发现什么?交易绝对不会中断。 https://firebase.google.com/docs/reference/admin/node/admin.database.Reference#transaction –

+0

我已将代码更改为包含onComplete和console.log。我的日志显示_current为null_(两次),_boolean为true_(一次),_snapshot为[object Object] _(一次),_Function执行耗时1297毫秒,结束状态为'ok'_(一次)。 @Doug –