Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Last active March 31, 2016 01:38
Show Gist options
  • Save cowboyd/da58760512e47668872e to your computer and use it in GitHub Desktop.
Save cowboyd/da58760512e47668872e to your computer and use it in GitHub Desktop.
An Ember helper to project a promise into a stream of POJO states
import Ember from 'ember';
export default Ember.Helper.extend({
compute([promise]) {
if (this.promise !== promise) {
this.promiseState = new PromiseState();
this.promise = promise;
this.promise.then((result)=> {
this.promiseState = this.promiseState.resolve(result);
this.recompute();
}).catch((reason)=> {
this.promiseState = this.promiseState.reject(reason);
this.recompute();
});
}
return this.promiseState;
}
});
class PromiseState {
constructor(attrs = {isResolved: false, isRejected: false}) {
Object.assign(this, attrs);
}
get isPending() {
return this.isResolved === false && this.isRejected === false;
}
get isSettled() {
return !this.isPending;
}
resolve(result) {
return new PromiseState({
isResolved: true,
isRejected: false,
result: result
});
}
reject(reason) {
return new PromiseState({
isResolved: false,
isRejected: true,
reason: reason
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment