Skip to content

Instantly share code, notes, and snippets.

@devongovett
Created July 30, 2011 17:52
Show Gist options
  • Save devongovett/1115785 to your computer and use it in GitHub Desktop.
Save devongovett/1115785 to your computer and use it in GitHub Desktop.
Asynchronous if statements in CoffeeScript
class Async
constructor: ->
@stack = []
@IF: (condition, fn) ->
async = new Async
async.stack.push (next) ->
if condition then fn(next) else next()
process.nextTick async.run.bind(async)
return async
ELSEIF: (condition, fn) ->
@stack.push (next) ->
if condition then fn(next) else next()
return this
ELSE: (fn) ->
@stack.push fn
return this
run: ->
stack = [@stack...]
do next = ->
fn = stack.shift()
fn(next)
module.exports = Async
Async.IF somecondition, ->
doSomething()
.ELSEIF someothercondition, ->
doSomethingElse()
.ELSE ->
anotherThing()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment