Today, I wrote C# like delegate class for CoffeeScript. This class executes the series callbacks step by step. Node.js requires devepolers to design non-blocking programs. So this implemtation is desinged using closures as the output of callbacks. If you are familiar to C# delegates, you may feels odd.
NOTICE: This class is a very simple implementation. If you are finding more powerful library like this, I suggest that you try async.
class Delegate
constructor: ()->
@callbacks = []
add: (callback)->
@callbacks.push(callback)
execute: (parameters, finalCallback)->
index = 0
parameters.unshift (error)=>
return finalCallback(error) if error
index += 1
if @callbacks[index]
@callbacks[index] parameters...
else
finalCallback(null)
@callbacks[index] parameters...
Basic usage:
delegate = new Delegate()
delegate.add (next, arg1, arg2)->
setTimeout ()->
console.log '#1', arg1, arg2
next()
, 500
delegate.add (next, arg1, arg2)->
setTimeout ()->
console.log '#2', arg1, arg2
next()
, 500
delegate.add (next, arg1, arg2)->
setTimeout ()->
console.log '#3', arg1, arg2
next()
, 500
delegate.execute ['hello', 'world!'], (error)->
console.log "#finial", error
This output is:
# 1 hello world!
# 2 hello world!
# 3 hello world!
# finial null
This class stops executing callbacks when detects an error in the middle.
delegate = new Delegate()
delegate.add (next)->
console.log '#2-1'
next(new Error("Something wrong..."))
delegate.add (next)->
console.log '#2-2'
next()
delegate.add (next)->
console.log '#2-3'
next()
delegate.execute [], (error)->
console.log "#2-finial", error
The output of this becomes like:
# 2-1
# 2-finial [Error: Something wrong...]