【问题标题】:how to use the promise '.then' component of transaction in firebase如何在firebase中使用事务的承诺'.then'组件
【发布时间】:2018-04-04 19:45:21
【问题描述】:

我正在使用 firebase 并且需要增加一个计数器,所以 transaction 似乎是最合适的竞争者。我了解交易使用承诺,但是我不清楚(并且手册没有示例)如何使用承诺的 .then 组件。

在原型制作的那一刻,我可以通过使用这样的警报来“放慢速度”:

var oldPosScore = firebase.database().ref('/data/n:'+stateNum[plus] + '/score/');
        oldPosScore.transaction (function(increment1) {
            alert ('POSITIVE statement number: ' + stateNum[plus] );            
            return ((increment1 || 0)*1 + 1);
        });

我用什么语法来设置它? .then 在这个用例中在哪里/如何工作?

EDIT(添加的数据结构): 我使用的是数字而不是 firebase 按键,因此我可以随机选择它们。

【问题讨论】:

    标签: javascript firebase firebase-realtime-database transactions promise


    【解决方案1】:

    您可以使用如下所示的交易承诺,

    var oldPosScore = firebase.database().ref('/data/n:'+stateNum[plus]);
    
        oldPosScore.child('score').transaction (function(increment1) {  
            return ((increment1 || 0)*1 + 1);
        }).then(function(){
          alert("transaction successfull");
    }).catch(function(err){
       alert(err);
    });
    

    见我的Js Fiddle Sample for Transaction "then" Promise

    我已经编辑了我的 Js 小提琴。看看它是否适合您?

    【讨论】:

    • 感谢您的回复,但我注意到您已将我的原始警报(用于减慢速度)留在原处。我尝试了你的建议,但如果我删除警报,它就不起作用......即它仍然没有写入 firebase 数据库。 return 应该在 .then 之后吗?
    • 你能告诉我你的数据结构,即你的 ref ref('/data/n:'+stateNum[plus] + '/score/');。我不明白为什么你要像这样使用 'data/n:'。
    • 已编辑问题现在显示数据结构及其原因:)
    • 您好,事务“return”完成后会将处理后的值更新到firebase数据库,然后调用promise。所以“return”应该是第一个,然后“then”调用才有效。
    • 嗨。我将 firebase ref 更改为您在 jsFiddle 中构建它的方式:var fbRef1 = firebase.database().ref('/data/n:'+stateNum[plus]); 然后fbRef1.child('score').transaction (function(increment1) 并且它正在工作。不知道为什么它会与child 一起使用,而不是与以前的参考一起使用。安排。想法?
    猜你喜欢
    • 2016-11-25
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2019-11-18
    • 2020-11-26
    • 1970-01-01
    相关资源
    最近更新 更多