p1100i
p1100i

Reputation: 3760

Is there an always callback for Ember.js .then function?

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.

Upvotes: 12

Views: 5582

Answers (4)

Taylor Allred
Taylor Allred

Reputation: 4380

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

Ember -> jQuery

  1. .then() -> .done()
  2. .catch() -> .fail()
  3. .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()
});

Upvotes: 12

yorbro
yorbro

Reputation: 1137

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.

Upvotes: 0

gorner
gorner

Reputation: 612

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;
  });
};

Upvotes: 2

Marcio Junior
Marcio Junior

Reputation: 19128

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

Upvotes: 3

Related Questions