Node.js中流程控制

Node.js中的流程控制可以使用async,在使用之前需要先安装,使用npm安装

npm install async --g

下面主要介绍4种流程控制的方式:

1、串行无关联:async.series(tasks,callback)

多个函数依次执行,之间没有数据交换,其中一个函数出错,后续函数不再执行;

以下是标准写法:

async.series({     
    one: function(callback){     
        callback(null, 1);     
    },     
    two: function(callback){     
        callback(null, 2);     
    }     
},function(err, results) {     
    console.log(results);     
});   

为了测试,我们使用交叉执行的方式:

var async = require('async');   
function exec(){  
    async.series({   
        one: function(done){  
            ii=0;  
            setInterval(function(){  
                console.log('aaa='+new Date());  
                ii++;  
                if(ii==3){  
                    clearInterval(this);  
                    done(null,{one:"one"});  
                }  
            },1000);  
        },  
        two: function(done){  
            jj=0;  
            setInterval(function(){  
                console.log('bbb='+new Date());  
                jj++;  
                if(jj>3){  
                    clearInterval(this);  
                    done(null,{two:"two"});  
                }  
            },1000);  
        }  
    },  
        function(err,rs) {   
            console.log(err);  
            console.log(rs);  
        });  
}  
exec();    

2、并行无关联:async.parallel(tasks,callback);     
多个函数并行执行,最后汇总结果,如果某一个流程出错就退出   

async.parallel({     
    one: function(callback){     
        callback(null, 1);     
    },     
    two: function(callback){     
        callback(null, 2);     
    }     
},function(err, results) {     
    console.log(results);     
});   

3、串行有关联:waterfall      
每一步执行时需要由上一步执行的结果当做参数.所以每一步必须串行等待

async.waterfall([     
    function (done) {     
     
        done(null, 'one');     
    },     
    function (onearg, done) {     
     
        done(null, onearg + '| two');     
    },     
    function (twoarg, done) {     
     
        done(null, twoarg + '| three');     
    },     
    function (threearg, done) {     
     
        done(null, threearg + '| four');     
    }     
], function (error, result) {     
    console.log(result);     
    console.timeEnd('waterfall');     
})  

4、parallelLimit(tasks, limit, [callback])
 parallelLimit函数和parallel类似,但是它多了一个参数limit。     
 limit参数限制任务只能同时并发一定数量,而不是无限制并发;

async.parallelLimit([     
    function(callback){     
        callback(null, 'one');     
    },     
    function(callback){     
        callback(null, 'two');     
    }     
],     
2, //只允许同时有两个函数并行     
function(err, results){     
    console.log(results);     
});

 

转载于:https://www.cnblogs.com/kefeiGame/p/9167584.html

Stepify(node-stepify) 是一个简单易扩展的Node.js流程控制引擎,采用方法链(methods chain)的方式定制异步任务,使得Node.js工作流易于理解和维护。 目标是将复杂的任务进行拆分成多步完成,使得每一步的执行过程更加透明,化繁为简。 stepify特点 最基本的API的就3个:step(),done(),run(),简单容易理解。 精细的粒度划分(同时支持单/多任务),执行顺序可定制化。 每一个异步操作都经过特殊的封装,内部只需要关心这个异步的执行过程。 链式(chain)调用,代码逻辑看起来比较清晰。 灵活的回调函数定制和参数传递。 统一处理单个异步操作的异常,也可根据需要单独处理某个任务的异常。 最简单的用法 简单实现基于oauth2授权获取用户基本资料的例子: // Authorizing based on oauth2 workflowStepify()     .step('getCode', function(appId, rUri) {         var root = this;         request.get('[authorize_uri]', function(err, res, body) {             root.done(err, JSON.parse(body).code);         });     }, [appId], [redirectUri])     .step('getToken', function(code) {         var root = this;         request.post('[token_uri]', function(err, res, body) {             root.done(err, JSON.parse(body).access_token);         });     })     .step('getInfo', function(token) {         request.get('[info_uri]?token='\u00a0 \u00a0token,\u00a0function(err,\u00a0res,\u00a0body)\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0//\u00a0got\u00a0user\u00a0info,\u00a0pass\u00a0it\u00a0to\u00a0client\u00a0via\u00a0http\u00a0response\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0});\n\u00a0\u00a0\u00a0\u00a0})\n\u00a0\u00a0\u00a0\u00a0.run();\n\u591a\u4e2astep\u5171\u7528\u4e00\u4e2ahandle\u3001\u9759\u6001\u53c2\u6570\u3001\u52a8\u6001\u53c2\u6570\u4f20\u9012\u7684\u4f8b\u5b50\uff1a\nStepify()\n\u00a0\u00a0\u00a0\u00a0.step('read', __filename)     .step(function(buf) {         // buf is the buffer content of __filename         var root = this;         var writed = 'test.js';         // do more stuff with buf         // this demo just replace all spaces simply         buf = buf.toString().replace(/\s /g, '');         fs.writeFile(writed, buf, function(err) {             // writed is the name of target file,             // it will be passed into next step as the first argument             root.done(err, writed);         });     })     .
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值