1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# like delegate implementation for CoffeeScript

Posted at

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.

delegate.coffee
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:

example.coffee
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.

error-example.coffee
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...]
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?