Skip to content

Instantly share code, notes, and snippets.

@micrypt
Last active August 29, 2015 14:04
Show Gist options
  • Save micrypt/e56c1ac844f1baf94fc8 to your computer and use it in GitHub Desktop.
Save micrypt/e56c1ac844f1baf94fc8 to your computer and use it in GitHub Desktop.
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