2014-08-30 113 views
2

我有一个简单的RSVP帮手,让我换一个Ajax调用一个简单的承诺如何链接RSVP承诺并返回原始拒绝/成功函数?

var PromiseMixin = Ember.Object.create({ 
    promise: function(url, type, hash) { 
     return new Ember.RSVP.Promise(function(resolve, reject) { 
      hash.success = function(json) { 
       return Ember.run(null, resolve, json); 
      }; 
      hash.error = function(json) { 
       if (json && json.then) { 
        json.then = null; 
       } 
       return Ember.run(null, reject, json); 
      }; 
      $.ajax(hash); 
     }); 
    } 
}); 

这个伟大的工程,是当时能够像你期望的那样。问题是,当我有需要另一个承诺的代码时,首先包装这个低级别的代码。

例如

在我的余烬控制器我可以这样做

 Appointment.remove(this.store, appointment).then(function() { 
      router.transitionTo('appointments'); 
     }, function() { 
      self.set('formErrors', 'The appointment could not be deleted'); 
     }); 

在我的约会模式,我做这行的“删除”

remove: function(store, appointment) { 
    return this.xhr('/api/appointments/99/', 'DELETE').then(function() { 
     store.remove(appointment); 
     //but how I do return as a promise? 
    }, function() { 
     //and how can I return/bubble up the failure from the xhr I just sent over? 
    }); 
}, 
xhr: function(url, type, hash) { 
    hash = hash || {}; 
    hash.url = url; 
    hash.type = type; 
    hash.dataType = "json"; 
    return PromiseMixin.promise(url, type, hash); 
} 

目前我的控制器总是落在进入“失败”状态(即使我的ajax方法返回204并成功)。我怎样才能在我的模型中从这个remove方法返回一个“链接诺言”返回值,以使控制器能够像上面那样将其作为“可靠”来调用它?

回答

3

难道你不能这样做吗?

remove: function(store, appointment) { 
    var self= this; 
    return new Ember.RSVP.Promise(function(resolve,reject) { 
     self.xhr('/api/appointments/99/', 'DELETE').then(function(arg) { 
      store.remove(appointment); 
      resolve(arg); 
     }, function(err) { 
      reject(err); 
     }); 
    }); 
}, 
+0

BOOM你钉我的朋友!对不起以前(不正确的评论)。正如你所说的,这成功了100%!再次感谢! – 2014-08-31 00:27:58