Skip to content

Instantly share code, notes, and snippets.

@edlin
Created July 17, 2012 18:17
Show Gist options
  • Save edlin/3131023 to your computer and use it in GitHub Desktop.
Save edlin/3131023 to your computer and use it in GitHub Desktop.
coffee utils
###
Async.js is a collection of simple async patterns
built to combat callback hell
###
###
ASYNC SEQUENCE
Allows a user to define a sequence of async functions.
EXAMPLE:
async = require 'async'
seq = new async.seq
seq.step ->
seq.val1 = 'a'
seq.next()
seq.step ->
seq.val2 = 'b'
seq.next()
seq.last ->
console.log( seq.val1 + seq.valb + ' should be ab' )
###
class Sequence
constructor: ->
@fn_queue = []
step: (fn) ->
@fn_queue.push fn
next: ->
if @fn_queue.length > 0
@fn_queue.shift()()
last: (fn) ->
@step fn
@next()
exports.seq = Sequence
###
ASYNC PARALLEL example - registers functions you want to run in parallel
---------------------------
require 'async'
parallel = new async.parallel 4 //timeout in seconds
parallel.register ->
doAsyncThing1 ->
parallel.finished()
parallel.register ->
doAsyncThing2 ->
parallel.finished()
parallel.complete ->
do w/e you need to do
###
class Parallel
constructor: (@timeoutSec = null) ->
@counter = 0
@completeFn = null
register: (fn) ->
@counter += 1
fn()
finished: () ->
@counter -= 1
if @counter > 0 then return
@completeFn()
if !@timeout then return
clearTimeout @timeout
complete: (fn) ->
@completeFn = fn
if @timeoutSec == null then return
@timeout = setTimeout =>
@completeFn()
, @timeoutSec * 1000
exports.parallel = Parallel
###
ASYNC LOOP
takes a function queue, data object, and final callback
loops through function queue using .next()
to move on to the next function in sequential order
uses 1 isntance of AsyncLoop
OPTIONAL - data, default is {}
###
class Loop
constructor: (@fn_queue, @data, @last={}) ->
if typeof @data == 'function'
[@last, @data] = [@data, @last]
for k, v of @data
@[k] = v if @[k] != 'next'
@next()
next: ->
if @fn_queue.length == 0
@end()
return
@fn_queue.shift() @
end: ->
@last @
exports.loop = (fn_queue, data, last) ->
new Loop fn_queue.slice(), data, last
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment