Skip to content
Homam Hosseini edited this page May 12, 2014 · 5 revisions

Promises as Monads

pure :: x -> Promise x

promise-monad.pure creates a promise from an object that resolves immediately.

fmap :: (x -> y) -> Promise x -> Promise y

promise-monad.fmap maps a normal function over a promise.

bind :: Promise x -> (x -> Promise y) -> Promise y

promise-monad.bind sequentially composes two promises, passing the value produced by the first as an argument to the second.

Example:

{promises: {promise-monad}} = require \async-ls
get = ->
	read = from-error-value-callback fs~read-file
	(data1) <- promise-monad.bind  read 'foo', 'utf8'
	(data2) <- promise-monad.bind  read 'bar', 'utf8'
	(data3) <- promise-monad.ffmap read 'baz', 'utf8'
	[data1, data2, data3]

get!.then do 
	(list) -> console.log map (.length), list # this will print a list of 3 integers (file sizes for foo, bar and baz).
	(error) -> console.log \error, error

`promise-monad` also has `ffmap` and `fbind` functions that are respectively flipped versions of `fmap` and `bind`.

Converting Promises to Callbacks

Use to-callback function:

(error, list) <- to-callback get!
console.log error, map (.length), list

Creating Promises

from-value-callback

from-error-value-callback

from-error-values-callback

from-named-callbacks

Asynchronous Operation on Lists

Map

Filter

Find

Any and All

Sort

Control Flow

Sequence

Waterfall