A simple Shared asynchronous operation manager for node. js

  • 2020-03-30 02:44:08
  • OfStack

Recently wrote nodejs is more, in the beginning of asynchronous operation is less, because want to do something relatively simple, check the API is synchronized, in order to save trouble with synchronization to directly, slowly found that this is not a thing ah, good asynchronous nature need not, must use synchronous, true � , and a lot of things without synchronization API.

Good! Writing asynchronous, this kind of code is slowly emerging...


mysql.query('xxxx').on('success', function(){
   mysql.query('xxxx').on('success', function(){
        mysql.query('xxxx').on('success', function(){
            mysql.query('xxxx').on('success', function(){
                mysql.query('xxxx').on('success', function(){
                    mysql.query('xxxx').on('success', function(){
                        //let's say fuck
                    });
                });
            });
        });
    });
});

En, you also see, so on the code more ugly, will be like the old lady's foot-binding cloth, then the generation of the following asynchronous operation manager, compact and exquisite, hey, absolutely enough to use, the code thing, with the code to speak, directly bright code, such as the code:

TODO: not comprehensive enough. For example, if something goes wrong, it is not handled


/*
 *   Asynchronous manager 
 *  author : jser.me
 *
 *   Usage: 
 *     var asyncMg = require('./AsyncManager');
 *     asyncMg
 *     .push(function( next ){
 *         some_aysnc_method().on('success'{
 *            ....
 *            next();
 *         })
 *     })
 *     .push(function( next ){
 *         other_aysnc_method().on('success'{
 *            ....
 *            next();
 *         })
 *     })
 *     .push( ... )
 *     .run() // perform 
 *     .on('success', function(){
 *          allThings_is_down();
 *     });
 *
 *     push Method accepts array 
 */
function typeOf( obj ){
    return Object.prototype.toString.call( obj ).match(/[object ([^]]*)]/)[1];
}
function AsyncManager( arg ){
    this.execArrys = [];
    this.push( arg );
}
//Use the inheritance method of system tape
require('util').inherits( AsyncManager, require('events').EventEmitter );
//Marks the number of functions that were successfully run
AsyncManager.prototype.succCount = 0;

// join 
AsyncManager.prototype.push = function( arg ) {
        var This = this;
        if( typeOf(arg) == 'Array' ){
            arg.forEach( function(v,i){
               This.execArrys.push( v );
            });
        } else {
               This.execArrys.push( arg );
        }
        return this; //A chain
};
// perform 
AsyncManager.prototype.run = function(){
        var self = this;
        if( this.succCount == this.execArrys.length ) {
            //Events are fired upon successful execution of all functions
            this.emit( 'success' );
        } else {
            this.execArrys[ this.succCount ]( self.run.bind( self ) );
        }
        this.succCount++;
        return this; //A chain
};
exports = module.exports = function( arg ){
    return new AsyncManager( arg );
}

 


Related articles: