2013-09-25 42 views
10

Giả sử tôi có một Ember obj. Khi làm bất kỳ loại đồng bộ với backend có một possiblity để sử dụng một chuỗi lời hứa:Luôn có một cuộc gọi lại cho hàm Ember.js .then?

obj.save().then(function(res){ 
    // Success callback 
}, function(res){ 
    // Fail callback 
}); 

Có một thực hiện/luôn gọi lại cho Ember.js chuỗi lời hứa với .then()?

Tôi đã thử thêm một chức năng tham số thứ ba, nhưng nó đã không giúp đỡ.

Trả lời

10

http://emberjs.com/api/classes/Ember.PromiseProxyMixin.html#method_finally

Ember -> jQuery

  1. .Sau đó() -> .done()
  2. .catch() -> .fail()
  3. .finally() - > .always()

Ví dụ (trong các bộ định tuyến):

var self = this; 
var modelType = this.store.createRecord('modelType', {/* model attrs */}); 

modelType.save().then(function(model){ 
    self.transitionTo('model.show', model); 
}).catch(function(){ 
    console.log('Failure to Save: ', reason); 
}).finally({ 
    self.hideSpinner() 
}); 
+1

Điều này phải được đánh dấu là câu trả lời chính xác. Công trình tuyệt vời cho tôi! – Pedro

3

Thật không may là không có. Nhưng bạn có thể tạo thay đổi của nguyên mẫu RSVP.Promise của bạn:

Ember.RSVP.Promise.prototype.always = function(func) { 
    return this.then(func, func); 
} 

Vì vậy, bạn có thể làm như sau:

// will show success 
Ember.RSVP.resolve('success').always(function(msg) { 
    alert(msg) 
}) 

// will show error 
Ember.RSVP.reject('error').always(function(msg) { 
    alert(msg) 
}) 

Tôi hy vọng nó giúp

2

Ember sử dụng thư viện RSVP.js cho những lời hứa, và RSVP does not support always do không phải là một phần của thông số Promises/A (+).

Nếu bạn cần nó, @wycats gợi ý following approach:

công trình giải pháp
Ember.RSVP.Promise.prototype.andThen = function(success, error, always) { 
    return this.then(function(value) { 
    var ret = success(value); 
    always(value); 
    return ret; 
    }, function(reason) { 
    var ret = error(reason); 
    always(reason); 
    return ret; 
    }); 
}; 
+0

Đủ công bằng, cảm ơn! – p1100i

+1

Ember có phương thức "cuối cùng": http://emberjs.com/api/classes/Ember.PromiseProxyMixin.html#method_finally – Taysky

0

gorner nhưng cho Ember Dữ liệu bạn cần phải thêm những điều sau đây cũng như:

Ember.PromiseProxyMixin.reopen({ 
    andThen: function() { 
    var promise = this.get('promise'); 
    return promise['andThen'].apply(promise, arguments); 
    } 
}); 

Nguyên nhân là do các Hàm DS.Model.save() trả về số PromiseObject (xem http://emberjs.com/api/data/classes/DS.PromiseObject.html), không thực hiện Ember.RSVP.Promise mà thay vào đó thực hiện Ember.PromiseProxyMixin. Vì vậy, bạn phải thực hiện chức năng andThen có sẵn trong mixin đó để nó hoạt động với các lời hứa khi lưu mô hình.

Các vấn đề liên quan