Skip to content

Instantly share code, notes, and snippets.

@weixiyen
Created September 29, 2011 06:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save weixiyen/1250084 to your computer and use it in GitHub Desktop.
Save weixiyen/1250084 to your computer and use it in GitHub Desktop.
###
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.next ->
seq.val1 = 'a'
seq.next()
seq.next ->
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: (fn) ->
@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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment