Skip to content

Instantly share code, notes, and snippets.

@walling
Forked from tcr/async.coffee
Created July 19, 2011 00:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save walling/1091019 to your computer and use it in GitHub Desktop.
Save walling/1091019 to your computer and use it in GitHub Desktop.
Lean and Mean Serial function in CoffeeScript
# Lean and Mean Serial DSL for CoffeeScript
# (based of https://gist.github.com/1090670 by timcameronryan)
serial = (spec) ->
commands = (func for key, func of spec when key != 'catch')
next = (err, args...) ->
return spec.catch(err) if err
commands.shift().apply(next, args) if commands.length > 0
next null
return
#########################
# serial test w/ mock fs
fs =
open: (_, _, cb) -> console.log('[fs.open]'); cb(0, {a_fake: 'file object'})
write: (f, _, cb) -> console.log('[fs.write]', f); cb(0, f)
close: (f, cb) -> console.log('[fs.close]', f); cb(0, f)
read: (f, cb) -> console.log('[fs.read]', f); cb(new Error 'not readable')
# Serial accepts a list of steps to execute in order.
# Use @/this as continuation and local storage.
# You can label your steps anything, but numbers look good:
serial
1: -> fs.open 'file', 'w', @
2: (@f) -> fs.write f, 'Apples', @
3: (written) -> fs.close @f, @
4: -> console.log 'Serial write test complete.'
catch: (err) ->
console.log "Write test failed: #{err.stack}"
# Example with failure:
serial
1: -> fs.open 'file', 'w', @
2: (@f) -> fs.read f, @
3: (read) -> fs.close @f, @
4: -> console.log 'Serial read test complete.'
catch: (err) ->
console.log "Read test failed: #{err.stack}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment