public
Created — forked from tcr/async.coffee

Lean and Mean Serial function in CoffeeScript

  • Download Gist
async.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
# 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}"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.