Last active
December 17, 2015 06:08
-
-
Save ukyo/5562844 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
class Promise | |
@STATE_PENDING = 2 | |
@STATE_RESOLVED = 1 | |
@STATE_REJECTED = 0 | |
constructor: -> | |
@_onResolved = null | |
@_onRejected = null | |
@_next = null | |
@_state = Promise.STATE_PENDING | |
then: (onResolved, onRejected) -> | |
@_onResolved = onResolved | |
@_onRejected = onRejected | |
@_next = new Deferred | |
@_next.promise | |
done: (onResolved) -> @then onResolved | |
fail: (onRejected) -> @then null, onRejected | |
always: (callback) -> @then callback, callback | |
class Deferred | |
@isPromise = (x) -> | |
x instanceof Promise or x and typeof x.then is 'function' | |
transition = (isResolve, promise, args) -> | |
return if !promise or promise._state isnt Promise.STATE_PENDING | |
next = promise._next | |
handler = [promise._onResolved, promise._onRejected][+!isResolve] | |
if typeof handler isnt 'function' | |
transition isResolve, next.promise, args if next | |
return | |
try | |
promise._state = +isResolve | |
result = handler args... | |
return if !next | |
if Deferred.isPromise result | |
result.then next.resolve, next.reject | |
else | |
transition isResolve, next.promise, [result] | |
catch reason | |
promise._state = Promise.STATE_REJECTED | |
transition false, next.promise, [reason] if next | |
constructor: -> @promise = new Promise | |
resolve: => transition true, @promise, arguments | |
reject: => transition false, @promise, arguments |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment