Skip to content

Instantly share code, notes, and snippets.

@jhartikainen
Created January 8, 2012 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhartikainen/1576557 to your computer and use it in GitHub Desktop.
Save jhartikainen/1576557 to your computer and use it in GitHub Desktop.
Function for executing things in parallel, because I couldn't find any I liked =)
parallel = (ops) ->
results = []
numOps = ops.length
errHandler = null
hadError = false
okHandler = null
for op, num in ops
do (num) ->
op (err, result) ->
# ignore if had an error earlier
if hadError
return
if err? and errHandler
hadError = true
return errHandler err
numOps--
results[num] = result
if numOps == 0 and not hadError
okHandler.apply {}, results
handlers = {
err: (errFn) ->
errHandler = errFn
return handlers
ok: (okFn) ->
okHandler = okFn
return handlers
}
return handlers
# Usage:
parallel([
(n) -> getFoos (err, foos) -> n(err, foos)
(n) -> getBars (err, bars) -> n(err, bars)
]).err((err) ->
# Execution goes here if any of the above functions produce an error
).ok((foos, bars) ->
# foos is now result of getFoos
# bars is now result of getBars
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment