您的位置:首页 > Web前端 > Node.js

nodejs 异步流程控制

2020-02-02 00:14 615 查看

先安装:     
G:\www\nodejs\study>npm install async --g     
     
1.串行无关联:async.series(tasks,callback);     
多个函数依次执行,之间没有数据交换,其中一个函数出错,后续函数不再执行     

//-------------nj_async.js------------------------------    

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      瀑布流
每一步执行时需要由上一步执行的结果当做参数.所以每一步必须串行等待     

var async = require('async');
function exec(){
async.waterfall(
[
function(done){
ii=0;
setInterval(function(){
console.log("aaa="+new Date());
ii++;
if(ii==3){
clearInterval(this);
done(null,'one完毕');
}
},1000);
},
function(preValue,done){ //上一函数的值
jj=0;
setInterval(function(){
console.log(preValue+"="+new Date());
jj++;
if(jj==3){
clearInterval(this);
done(null,preValue+',two完毕');
}
},1000);

}
],function(err,rs){
console.log(err);
console.log(rs);
}
)
}

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

转载于:https://www.cnblogs.com/yin-dt/p/8076164.html

  • 点赞 1
  • 收藏
  • 分享
  • 文章举报
angchisi1289 发布了0 篇原创文章 · 获赞 1 · 访问量 123 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: