如何使用then更新firebase中的多个节点

时间:2014-01-01 21:54:47

标签: angularjs firebase angularfire

我想更新firebase中的几个节点,因为数据是非规范化的。因此,更新每个节点时必须等到以前的更新成功。

所以我有下面的东西(我目前使用的东西),你可以看到如果要更新更多节点,它是不可读的。

if(foo1) {
  firebaseRef.update(data, function(error) {
    if(error){
      console.log(error);
    } else {
      firebaseRef.update(data, function(error){
        if(error){
          console.log(error);    
        }else{
          //Update Another
        };
      });
    };
  });
};

所以任何想法如何在.then或纯火山angularFire中使用js api

firebaseRef().then(function(){
    return doSomething;
}).then(function(){
    return doSomething;
}).then(function(){
    return doSomething;
}).then(function(){
    return doSomething;
});

1 个答案:

答案 0 :(得分:2)

目前Firebase或AngularFire没有未来。所以你需要使用装饰器/包装器策略。

jQuery的:

function update(ref, data) {
   $.Deferred(function(def) {
      ref.update(data, function(err) {
         if( err ) def.reject(err);
         else      def.resolve();
      });
   });
}

var fb = new Firebase(URL);
update(fb.child('path1'), 'foo')
   .then(update.bind(null, fb.child('path2'), 'bar'))
   .then(update.bind(null, fb.child('path3'), 'foobar'))
   .done(function() { console.log('yay!'); });

角:

angular.service('update', function($q, $timeout) {
   return function(ref, data) {
      var def = $q.defer();
      ref.update(data, function(err) {
        if( err ) def.reject(err);
        else      def.resolve();
      });
      return def.promise;
   }
});

angular.controller('ctrl', function(update) {
   var fb = new Firebase(URL);
   update(fb.child('path1'), 'foo')
       .then(update.bind(null, fb.child('path2'), 'bar'))
       .then(update.bind(null, fb.child('path3'), 'foobar'))
       .done(function() { console.log('yay!'); });
});

绑定polyfill(与期货相当方便):https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility

如果您更喜欢这种语法,也可以在不使用.bind的情况下关闭它:

function updateHandler(ref, data) {
   return function() {
      $.Deferred(function(def) {
         ref.update(data, function(err) {
            if( err ) def.reject(err);
            else      def.resolve();
         });
      });
   }
}

var fb = new Firebase(URL);
updateHandler(fb.child('path1'), 'foo')()
   .then(updateHandler(fb.child('path2'), 'bar'))
   .then(updateHandler(fb.child('path3'), 'foobar'))
   .done(function() { console.log('yay!'); });
相关问题