2014-08-30 38 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