Last active
August 29, 2015 14:04
-
-
Save micrypt/e56c1ac844f1baf94fc8 to your computer and use it in GitHub Desktop.
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
Promise = (fn) -> | |
state = 'pending' | |
value = deferred = null | |
resolve = (newValue) -> | |
if newValue and typeof newValue.then is 'function' | |
newValue.then resolve, reject | |
return | |
state = 'resolved' | |
value = newValue | |
if deferred | |
handle deferred | |
return | |
reject = (reason) -> | |
state = 'rejected' | |
value = reason | |
if deferred | |
handle deferred | |
return | |
handle = (handler) -> | |
if state is 'pending' | |
deferred = handler | |
return | |
if state is 'resolved' | |
handlerCallback = handler.onResolved | |
else | |
handlerCallback = handler.onRejected | |
if not handlerCallback | |
if state is 'resolved' | |
handler.resolve value | |
else | |
handler.reject value | |
return | |
try | |
ret = handlerCallback value | |
catch e | |
handler.reject e | |
return | |
handler.resolve ret | |
return | |
@then = (onResolved, onRejected) -> | |
new Promise -> | |
handle | |
onResolved: onResolved | |
onRejected: onRejected | |
resolve: resolve | |
reject: reject | |
return | |
fn resolve, reject | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment