Skip to content

Instantly share code, notes, and snippets.

@nat-n
Created September 3, 2012 14:48
Show Gist options
  • Save nat-n/3609831 to your computer and use it in GitHub Desktop.
Save nat-n/3609831 to your computer and use it in GitHub Desktop.
In the smallest possible Coffeescript code, chain an array of async callbacks to "thread" their evaluation order. Inspired from Haskell
# this should do the same thing with less code by using the array of functions as a LIFO stack
exec_cb_stack = (stack) =>
cb = () =>
stack.pop() cb if stack.length
stack.pop() cb
#
# example usage
#
final_fn = () -> alert('goodbye')
other_fns = []
iters = ['greetings','how do you do?']
for i in iters
other_fns.push ((cb)-> alert(iters.shift()); cb())
exec_cb_stack [final_fn].concat(other_fns)
# Construct a chained array of callbacks that "thread" a sequence of async functions in the smallest possible code.
# tldr; call the next async function in fn, "wait" for its callback to store the result and call the next async callback in cb
# each async function
# accepts 1 callback argument
# passes 1 arg of result data to the callback
# construct the callback
# when callback in cb evaluates, replaces itself in cb array with the result
# calls the next callback in cb
# after last callback in cb, return joined results stored in cb
monadik = (fn,fnend) ->
cb = []
(f = (k) ->
if k isnt fn.length
k1 = k+1
cb[k] = (d) ->
cb[k] = d
if k1 is fn.length then fnend(cb)
else fn[k1] (d) -> cb[k1](d)
f k1)(0)
fn[0] cb[0]
monadik [some_async_fn1, some_async_fn2], (res) ->
console.log "monadik done res "+res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment