Skip to content

Instantly share code, notes, and snippets.

@ukyo
Last active December 17, 2015 06:08
Show Gist options
  • Save ukyo/5562844 to your computer and use it in GitHub Desktop.
Save ukyo/5562844 to your computer and use it in GitHub Desktop.
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