Last active
March 31, 2016 01:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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