Skip to content

Instantly share code, notes, and snippets.

@NeoTech
Last active September 22, 2015 13:58
Show Gist options
  • Save NeoTech/cbd415e6df7b86a79217 to your computer and use it in GitHub Desktop.
Save NeoTech/cbd415e6df7b86a79217 to your computer and use it in GitHub Desktop.
A simplified example of Middleware execution.
/** This is a common question im running into, what is the difference between a promise design pattern and a middleware.. **/
/* This pattern is commonly found in connect, koa, express and other middleware based frameworks. */
/* This is not a hook pattern with pre/post */
function Middleware() {
if (!(this instanceof Middleware)) {
if (global.MODE_LVL < 5) {
console.log('Not an instance; returning new callbackStack Client');
}
return new Middleware();
}
var _self = this;
_self.middlewares = new Array();
}
Middleware.prototype.use = function(func) {
/* Adds to execution stack, return promise of next() */
var _self = this;
_self.middlewares.push(func);
return _self;
};
Middleware.prototype.exec = function() {
/* Runs the middleware stack and handles the callbacks in subsequent order. */
var index = 0;
var stack = this.middlewares;
function next(err) {
if(err) {
console.log(err);
}
var s = stack[index++];
if(!s) {
return;
}
/* Starts the after evaluation iteration */
call(s, next);
}
function call(s, next) {
/* Executes the callback */
try {
s(next);
} catch (e) {
error = e;
}
next(error);
}
next();
};
/* Example of useage */
var c = new Middleware();
c.use(function(next) {
console.log('1');
next();
}).use(function(next) {
console.log('2');
next();
}).exec();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment