Skip to content

Instantly share code, notes, and snippets.

@homam
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save homam/2a315ca711517fd3db47 to your computer and use it in GitHub Desktop.

Select an option

Save homam/2a315ca711517fd3db47 to your computer and use it in GitHub Desktop.
Binding ES6 Promises
unit = (x) -> new Promise (resolve, reject) ->
resolve x
# or just unit = -> Promise.resolve it
double = (x) -> new Promise (resolve, reject) ->
<- set-timeout _, 500
resolve 2 * x
square-root = (x) -> new Promise (resolve, reject) ->
<- set-timeout _, 500
return reject Error "Square root of negative number #{x} is not real." if x < 0
resolve Math.sqrt x
# m a -> (a -> m b) -> m b
bind = (p, f) -->
(resolve, reject) <- new Promise _
p.then do
resolve . f
reject
# Promise a -> IO ()
run = (p) ->
p.then do
-> console.log it
-> console.log "error #it"
# Promise a -> IO ()
run do ->
x <- bind unit 3
x := x * 12
y <- bind double x
z <- bind double y
a <- bind square-root z * -1 # create an error
a := 10 * a
double a
unit = (x) -> new Promise (resolve, reject) ->
resolve x
# or just unit = -> Promise.resolve it
double = (x) -> new Promise (resolve, reject) ->
<- set-timeout _, 500
resolve 2 * x
# m a -> (a -> m b) -> m b
bind = (p, f) -->
new Promise (resolve, reject) ->
p.then do
-> resolve <| f it
-> reject it
# Promise a -> IO ()
run = (p) ->
p.then do
-> console.log it
-> console.log "error #it"
# Promise a
run do ->
x <- bind unit 3
x := x * 12
y <- bind double x
double y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment