Skip to content

Instantly share code, notes, and snippets.

@walling
Created July 27, 2011 10:55
Show Gist options
  • Save walling/1109144 to your computer and use it in GitHub Desktop.
Save walling/1109144 to your computer and use it in GitHub Desktop.
Serial/Parallel
module.exports = serial = (spec) ->
steps = (func for key, func of spec when key != 'catch')
raise = (err) -> if spec.catch then spec.catch err else throw err
next = (err, args...) ->
return raise(err) if err
steps.shift().apply(next, args) if steps.length > 0
next._count = 0
next._result = []
next.parallel = ->
next._count++
(err, value) ->
return raise(err) if err
next._result.push value
if next._count == next._result.length and steps.length > 0
steps.shift().apply(next, next._result)
next null
return
after_a_while = (value, callback) ->
setTimeout ->
callback null, value
, 1000
serial
1: ->
after_a_while 'Wow', @
2: (wow) ->
console.log wow
after_a_while 'Hello', @parallel()
after_a_while 'World', @parallel()
3: (sentence...) ->
console.log sentence
setTimeout (=> @ new Error 'Blah!'), 500
4: ->
console.log 'This is never printed!'
catch: (err) ->
console.log err.stack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment