/*
* Async Manager
* author : jser.me
*
* Usage:
* var asyncMg = require('./AsyncManager') ;
* asyncMg
* .push(function(next){
* some_aysnc_method().on('success'{
* next();
* . next( );
* })
* })
* .push( ... )
* .run() //Execute
* .on('success', function() {
* allThings_is_down();
* });
function typeOf( obj ){
return Object.prototype.toString.call( obj ).match(/[object ([^]]*)]/)[1];
}
function AsyncManager( arg ){
this.execArrys = [];
this.push( arg );
}
//Use the inheritance method provided by the system
require('util').inherits( AsyncManager, require('events').EventEmitter );
//Mark the number of successfully run functions
AsyncManager.prototype.succCount = 0;
//Add
AsyncManager.prototype.push = function( arg ) {
var This = this;
if( typeOf(arg) == 'Array' ){
arg.forEach( function(v,i){
This.execArrys.push( v );
});
return this; //Chain one
};
//Execute
AsyncManager.prototype.run = function(){
var self = this;
If( this.succCount == this.execArrys.length ) {
//Events are triggered after all functions are successfully executed
this.emit( 'success' );
} else {
this.execArrys[ this.succCount ]( self.run.bind( self ) );
}
this.succCount ;
return this; //Chain one
};
exports = module.exports = function( arg ){
return new AsyncManager( arg );
}