Created
July 27, 2011 10:55
-
-
Save walling/1109144 to your computer and use it in GitHub Desktop.
Serial/Parallel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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