sendAction as a promise

@seif I’ve been thinking about something very similar lately. I spoke to @machty about it and he pointed me to a computed property that he’s been using.

// A PromiseAction is an action set on the controller,
// but not in the actions hash, which allows it to be
// passed in directly to the component. The component
// just sees it as a function that it can call that
// returns a promise. This is nice for when the component
// needs to emit some action that can fail; if it fails
// it can clean up after itself.
 
// Example:
// export default Controller.extend({
//   setSomeValueAsyncly: promiseAction(function(newValue) {
//     this.set('something', newValue);
//     // simulate a slow set...
//     return new Ember.RSVP.Promise(function(resolve) {
//       Ember.run.later(resolve, 1000);
//     });
//   })
// });
//
// {{some-component on-change=setSomeValueAsyncly}}
 
export default function promiseActionComputedProperty(fn) {
  return Ember.computed(function() {
    var self = this;
    return function() {
      var args = arguments;
      return new Ember.RSVP.Promise(function(resolve) {
        resolve(fn.apply(self, args));
      });
    };
  });
};

I’m looking at how I can use it myself but I just wanted to share.

2 Likes