firebase云功能事务偶尔工作 [英] firebase Cloud function transaction working sporadically

查看:91
本文介绍了firebase云功能事务偶尔工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有这样的云功能:

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

It fires consistently as I can see the log entries. However, the newsCnt field is not updated as expected. Sometimes it gets updated and sometimes not!!! What am I doing wrong here?

推荐答案

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

You should expect that a transaction be called potentially multiple times, the first time with null. That's the way transactions work. Please read the documentation here.

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

In particular note the following callout in that section:


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

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云功能事务偶尔工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆