NextFlow: Sane CoffeeScript Flow Control

Take a look at the most prominent JavaScript control flow libraries: Async.js, Step, Seq. If you were to use these libraries in CoffeeScript, your code would be an ugly mess.

Async.js / CoffeeScript

async = require('async')

async.series(
  (->
    #first function
  ),
  (->
    #second function
  )
)

Step / CoffeeScript

Step = require('step')

Step(
  (->
    #first function
  ),
  (->
    #second function
  )
)

Seq / CoffeeScript

Seq = require('seq')

Seq().seq(->
  #first function
).seq(->
  #second function
)

Yuck. If you're programming in JavaScript, all of them are very usable solutions. Also, to be fair, they do a lot more than NextFlow. But NextFlow looks much nicer with CoffeeScript programs.

How to Install:

npm install --production nextflow

Can be used in the browser too.

Execute sequentially, calling the `next()` function:

next = require('nextflow')

vals = []
x = 0

flow =
  1: ->
    vals.push(1)
    @next()
  2: ->
    vals.push(2)
    x = Math.random()
    @next(x)
  3: (num) ->
    vals.push(num)
    @next()
  4: ->
    vals.push(4)
    @next()
  5: ->
    console.log vals[0] #is 1
    console.log vals[1] #is 2
    console.log vals[2] #is x
    console.log vals[3] #is 4

next(flow)

Call functions by the label:

vals = []
x = 0

flow =
  a1: ->
    vals.push(1)
    @a2()
  a2: ->
    vals.push(2)
    x = Math.random()
    @a3(x)
  a3: (num) ->
    vals.push(num)
    @a4()
  a4: ->
    vals.push(4)
    @a5()
  a5: ->
    console.log vals[0] #is 1
    console.log vals[1] #is 2
    console.log vals[2] #is x
    console.log vals[3] #is 4

next(flow)

Call either `next()` or call the label:

vals = []
x = 0
y = 0

flow =
  a1: ->
    vals.push(1)
    @a2()
  a2: ->
    vals.push(2)
    x = Math.random()
    @a3(x)
  a3: (num) ->
    vals.push(num)
    y = Math.random()
    @next(y)
  a4: (num) ->
    vals.push(num)
    @a5()
  a5: ->
    console.log vals[0] #is 1
    console.log vals[1] #is 2
    console.log vals[2] #is x
    console.log vals[3] #is y

next(flow)

NextFlow on Github

If you made it this far, you should follow me on Twitter.

-JP

Want to test-drive Bitcoin without any risk? Check out my bitcoin wallet Coinbolt. It includes test coins for free.

comments powered by Disqus