Skip to content

Instantly share code, notes, and snippets.

@sukima
Last active August 7, 2016 19:41
Show Gist options
  • Select an option

  • Save sukima/ab704382cc1d28312aa6785f3c642f75 to your computer and use it in GitHub Desktop.

Select an option

Save sukima/ab704382cc1d28312aa6785f3c642f75 to your computer and use it in GitHub Desktop.
PromiseProxyMixin UI feedback
import Ember from 'ember';
import { makeTestPromise } from '../utils/test-foo';
const TestFoo = Ember.Object.extend(Ember.PromiseProxyMixin, {
init() {
// By default a PromiseProxy will rethrow a
// rejected promise causing it to be left
// unhandled. Since by the nature of this use
// pattern it is handled (see template) we add
// a no-op to the end of the chain and the
// rejection will be concidered handled.
this.catch(() => {});
}
});
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
actions: {
test() {
const promise = makeTestPromise();
this.set('foo', TestFoo.create({promise}));
}
}
});
body {
margin: 12px 16px;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12pt;
}
.info {
color: lightblue;
}
.success {
color: green;
}
.danger {
color: red;
}
<h1>Welcome to {{appName}}</h1>
<button {{action "test"}}>Click!</button>
{{#unless foo}}
<p>Click the button to spawn a promise and see the result.</p>
{{/unless}}
{{#if foo.isPending}}
<p class="info">Loading…</p>
{{/if}}
{{#if foo.isFulfilled}}
<p class="success">{{foo.content}}</p>
{{/if}}
{{#if foo.isRejected}}
<p class="danger">{{foo.reason}}</p>
{{/if}}
<p><small>Each promise has a 50/50 chance of resolving or rejecting</small></p>
{
"version": "0.8.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.5.1",
"ember-data": "2.5.2",
"ember-template-compiler": "2.5.1"
}
}
import Ember from 'ember';
export function rand(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
export function makeTestPromise() {
return new Ember.RSVP.Promise((resolve, reject) => {
const time = rand(500, 2000);
const willResolve = rand(1, 100) % 2 === 0;
Ember.run.later(() => {
if (willResolve) {
resolve('Works');
} else {
reject(new Error('Failed!'));
}
}, time);
}, 'TestPromise');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment