async
异步的串行执行(有先后顺序)
async.series([function(callback){
fs.readFile('file1.txt','utf-8',callback)
},function(callback){
fs.readFile('file2.txt','utf-8',callback)
}],function(err,results){
//results => [file1.txt,file2.txt]
})
series()适合无依赖的异步串行执行,但当前一个的结果是后一个调用的输入时,series()就无法满足需求。下面介绍的waterfall()可以解决这个问题
异步调用的依赖处理
async.waterfall([
function(callback){
fs.readFile('file1.txt','utf-8',function(err,content){
callback(err,content);
});
},
function(arg1,callback){
//arg1 => file2.txt
fs.readFile(arg1,'utf-8',function(err,content){
callback(err,content);
});
},
function(arg1,callback){
//arg1 => file3.txt
fs.readFile(arg1,'utf-8',function(err,content){
callback(err,content)
});
}
],function(err,result){
//result => file4.txt
})
异步的并行执行(同时进行)
async.parallel([function(callback){
fs.readFile('file1.txt','utf-8',callback)
},function(callback){
fs.readFile('file2.txt','utf-8',callback)
}
],function(err,results){
//results => [file1.txt,file2.txt]
})
自动依赖处理
在现实的业务环境中,具有很多复杂的依赖关系,有异步的也有同步的,经常让人感觉混乱,理不清顺序,为此async提供一个强大的方法auto()实现业务处理
如下面这个例子:
connectMongoDB和connectRedis依赖readConfig,uploadAsserts依赖compileAsserts,startup则依赖所有完成,依赖关系如下
var deps = {
readConfig:function(callback){
//rad config file
callback();
},
connectMongoDB:['readConfig',function(callback){
//connect to mongodb
callback();
}],
connectRedis:['readConfig',function(callback){
//connect to redis
callback();
}],
complieAsserts:function(callback){
//compile asserts
callback();
},
uploadAsserts:['compileAsserts',function(callback){
//upload to assert
callback();
}],
startup:['connectMongoDB','connectRedis','uploadAsserts',function(callback){
//start up
}]
}
async.auto(deps);// auto方法能根据依赖关系自动分析,以最佳的顺序执行以上业务