链接多个firebase操作和回滚

时间:2016-03-28 16:40:35

标签: javascript firebase chaining

我正在使用firebase,我想链接一些动作。这是场景: 我想在数组中添加一个项目,因为我不想使用推送ID,我更新了一个' Last_Id'每次添加项目时,firebase中的变量。我还更新了一个' Counter'变量来计算记录的数量(所以我不会最终使用numChildren(),这可能很慢)。 count和last_id变量在同一个树中,如下所示: 字数:
----------> last_id
---------->计数器
我这样做是为了在一次交易中同时更新它们

所以当我添加一个项目时,我想要按顺序发生三件事:

  1. 1- last_id已被检索

  2. 项目已添加

  3. last_id和Counter是 都更新了
  4. 这是我使用promises的代码。

    add:function(ref,obj){
    
         //get last_id
        return baseRef.child('Count').child("Last_Id").once("value")
                .then(function(snapshot){
                  return (snapshot.val()+1);
                })
        //add new data
              .then(function(key){
                   return baseRef.child(ref).child(key).set(obj,function(error){ 
                        if (error)
                           console.log(error.code)
                        })    
               })
       //update Count and last key
               .then(this.updateCountAndKey(ref,1))
    
    
    },
    
    
    updateCountAndKey:function(ref,i){
       return baseRef.child('Count').transaction(function(currentValue) {
          if (currentValue!==null)
                return {
                     Counter:(currentValue.Counter||0) +i,
                     Last_Id:(currentValue.Last_Id||0)+1
                     }
        },function(err,commited,snap) {
            if( commited ) 
               console.log("updated counter to "+ snap.val());
            else {
                console.log("oh no"+err);
            }
        },false)
    
    }
    

    因为我是javascript的新手,特别是承诺想知道这是否是一种强有力的做事方式。如果出现问题,我也想知道如何进行回滚。所以,如果一件事失败,那么其他一切都会失败(例如,如果对Last_id和Counter的更新失败,那么该项目就不会被添加)。 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

正如Firebase documentation指定的那样,交易只能Atomically modify the data at this location,因此您无法使用事务更新Firebase中的其他节点。

建议使用推送ID(由Firebase以安全的方式生成)。这将消除对流程的这一部分使用事务的需要。如果需要维护计数,则仍需要使用事务。这应该在#2(添加项目)成功时完成。

现在您的流程将如下所示:

  1. 推送项目(自动生成的ID)
  2. 成功时,使用事务递增计数