Skip to content

Instantly share code, notes, and snippets.

@rjungemann
Created February 17, 2011 17:12
Show Gist options
  • Save rjungemann/832149 to your computer and use it in GitHub Desktop.
Save rjungemann/832149 to your computer and use it in GitHub Desktop.
Different flow control ideas for CoffeeScript ("normal", "step", and "hop")
# odd synchronus patterns -- purported 'monadic' flow control
events = require 'events'
step = (callback) ->
first = true
queue = []
emitter = new events.EventEmitter
this.step = (callback) ->
queue.push callback
if queue.length == 1
emitter.emit 'ready'
next = ->
c = queue.shift()
if c
c next
else
listener = (e) ->
emitter.removeListener 'ready', listener
c = queue.shift()
c next
emitter.on 'ready', listener
process.nextTick ->
if first
first = false
next()
this
this.step callback
hop = (callback) ->
first = true
queue = []
emitter = new events.EventEmitter
f = (callback) ->
queue.push callback
if queue.length == 1
emitter.emit 'ready'
next = ->
c = queue.shift()
if c
c next
else
listener = (e) ->
emitter.removeListener 'ready', listener
c = queue.shift()
c next
emitter.on 'ready', listener
process.nextTick ->
if first
first = false
next()
f
f callback
module.exports = {
step: step
hop: hop
}
# examples of using various flow controls to sequence asynchronous events
if process.argv.indexOf 'test' > -1
# an example of 'normal' sequenced flow control, aka "boomerang code"
console.log 'normal'
(->
console.log 1
(->
console.log 2
(-> console.log 3)()
)()
)()
# monadic, somewhat jQuery-ish idiom. Chained methods become sequenced
console.log 'step'
step((next) -> console.log 1; next()).
step((next) -> console.log 2; next()).
step((next) -> console.log 3)
# combinatorial idiom. Each function returns a new function
timer = ->
console.log 'hop'
hop(
(next) -> console.log 1; next()
)(
(next) -> console.log 2; next()
)(
(next) -> console.log 3; next()
)
setTimeout timer, 1
# outputs:
#
# normal
# 1
# 2
# 3
# step
# 1
# 2
# 3
# hop
# 1
# 2
# 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment