一個簡單的Node.js非同步作業管理器分享

來源:互聯網
上載者:User

最近寫nodejs比較多,剛開始的時候碰到的非同步操作比較少,因為想做的東西比較簡單,一查api有同步的,為了省事就直接用同步的搞了,慢慢發現這不是個事呀,好好的非同步特性不用,非得用同步的,真囧,並且很多東西木有同步的api的。

好!寫非同步,慢慢的出現了這種代碼。。。
複製代碼 代碼如下:
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
                    });
                });
            });
        });
    });
});
恩,你也看到了,這樣下去代碼多醜,會像老太太的裹腳布一樣了,於是就產生下面的非同步作業管理器,小巧精緻,嘿嘿,絕對夠用,代碼的事,用代碼說話吧,直接亮代碼,如碼:

TODO:不夠全面,比如說出錯的就沒有處理
複製代碼 代碼如下:
/*
 *  非同步管理器
 *  author : jser.me
 *
 *  使用方法:
 *     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() //執行
 *     .on('success', function(){
 *          allThings_is_down();
 *     });
 *
 *     push方法接受數組
 */

function typeOf( obj ){
    return Object.prototype.toString.call( obj ).match(/\[object ([^\]]*)\]/)[1];
}

function AsyncManager( arg ){
    this.execArrys = [];
    this.push( arg );
}

//使用系統帶的繼承方法
require('util').inherits( AsyncManager, require('events').EventEmitter );

//標記成功啟動並執行函數數目
AsyncManager.prototype.succCount = 0;


//加入
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; //鏈一個
};

//執行
AsyncManager.prototype.run = function(){
        var self = this;

        if( this.succCount == this.execArrys.length ) {
            //所有函數成功執行後觸發事件
            this.emit( 'success' );
        } else {
            this.execArrys[ this.succCount ]( self.run.bind( self ) );
        }

        this.succCount++;
        return this; //鏈一個
};

exports = module.exports = function( arg ){
    return new AsyncManager( arg );
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.