gpt4 book ai didi

firebase云功能事务偶尔工作

转载 作者:行者123 更新时间:2023-12-02 21:44:00 25 4
gpt4 key购买 nike

我有这样的云功能:

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 字段并未按预期更新。有时更新有时不更新!!!我在这里做错了什么?

最佳答案

您应该预料到一个事务可能会被多次调用,第一次时为 null。这就是交易的运作方式。请阅读文档here .

特别注意该部分中的以下标注:

Note: Because your update function is called multiple times, it must be able to handle null data. Even if there is existing data in your remote database, it may not be locally cached when the transaction function is run, resulting in null for the initial value.

关于firebase云功能事务偶尔工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44481979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com