Assume I got an Ember obj
. When doing any kind of sync with backend there is a possiblity to use a promise chain:
obj.save().then(function(res){
// Success callback
}, function(res){
// Fail callback
});
Is there a done/always callback for Ember.js promise chain with .then()
?
I've tried adding a third parameter function, but it did not help.
Assume I got an Ember obj
. When doing any kind of sync with backend there is a possiblity to use a promise chain:
obj.save().then(function(res){
// Success callback
}, function(res){
// Fail callback
});
Is there a done/always callback for Ember.js promise chain with .then()
?
I've tried adding a third parameter function, but it did not help.
Share Improve this question asked Sep 25, 2013 at 11:23 p1100ip1100i 3,7402 gold badges31 silver badges45 bronze badges4 Answers
Reset to default 12http://emberjs.com/api/classes/Ember.PromiseProxyMixin.html#method_finally
Ember -> jQuery
- .then() -> .done()
- .catch() -> .fail()
- .finally() -> .always()
Example (in the router):
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()
});
Unfortunately there isn't. But you can create your own modifying the RSVP.Promise
prototype:
Ember.RSVP.Promise.prototype.always = function(func) {
return this.then(func, func);
}
So you can do the following:
// will show success
Ember.RSVP.resolve('success').always(function(msg) {
alert(msg)
})
// will show error
Ember.RSVP.reject('error').always(function(msg) {
alert(msg)
})
I hope it helps
Ember uses the RSVP.js library for promises, and RSVP does not support always
due to not being part of the Promises/A(+) specs.
If you need it, @wycats suggests the following approach:
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;
});
};
gorner's solution works but for Ember Data you have to add the following as well:
Ember.PromiseProxyMixin.reopen({
andThen: function() {
var promise = this.get('promise');
return promise['andThen'].apply(promise, arguments);
}
});
The reason is that the DS.Model.save()
function returns a PromiseObject
(see http://emberjs.com/api/data/classes/DS.PromiseObject.html), which doesn't implement Ember.RSVP.Promise
but instead implements Ember.PromiseProxyMixin
. So you have to make the andThen
function available in that mixin in order for it to work with promises when saving models.