ember.js PromiseProxyMixin


Example

Ember comes with a built in helper that will provide computed properties for the status of an asynchronous task.

Pros

  • Built in – no need for an addon.
  • Can be managed in the life cycle of a component.
  • Provides convenient state properties that can drive the template logic.

Cons

  • Must be wrapped in an Ember.Object and cannot be applied to an Ember.Component directly.
  • Creates a disconnect between the original promise chain and the destructing of the content value.
  • Is not very intuitive and can be difficult to reason with.
  • Cannot be cancelled.

JavaScript

import Ember from 'ember';

const {
  Component, PromiseProxyMixin, get, set, computed,
  isPresent, run, RSVP: { Promise }
} = Ember;

const MyPromiseProxy = Ember.Object.extend(PromiseProxyMixin);

export default Component({
  myProxy: computed('promise', {
    get() {
      const promise = get(this, 'promise');
      return isPresent(promise) ? MyPromiseProxy.create({promise}) : null;
    }
  }),

  actions: {
    performTask() {
      const fakeTask = new Promise((resolve) => {
        run.later(resolve, 'Foobar', 2000);
      });
      set(this, 'promise', fakeTask);
    }
  }
});

Template

{{#if myProxy.isPending}}
  Loading…
{{else}}
  <button onclick={{action "performTask"}}>
    Start Task
  </button>
{{/if}}

{{#if myProxy.isFulfilled}}
  Done. {{myProxy.content}}
{{/if}}

{{#if myProxy.isRejected}}
  Something went wrong. {{myProxy.reason}}
{{/if}}