https://www.npmjs.com/package/async
PART 1
http://yijiebuyi.com/blog/be234394cd350de16479c583f6f6bcb6.html
本篇算是async庫的速查手冊吧,詳細(xì)學(xué)習(xí)參考一下上面貼的鏈接
這個(gè)是aearly寫的async庫,和ES6自帶的async不是一個(gè)東西
串行 無關(guān)聯(lián) async.series
函數(shù)依次執(zhí)行,后面不需要調(diào)前面步驟的結(jié)果
async.series(
{
func1: function(done){
//done(err, 參數(shù)): 將參數(shù)寫入results.func1
done(err, 數(shù)據(jù)1) //results.func1 = 數(shù)據(jù)1
done(err, 數(shù)據(jù)1, 數(shù)據(jù)2) //表現(xiàn)為數(shù)組,results.func1 = [數(shù)據(jù)1, 數(shù)據(jù)2]
},
func2: function(done){
done(err, 參數(shù))
},
},
function(error, results){
//results.func1, results.func2...
}
});
串行 有關(guān)聯(lián) async.waterfall
函數(shù)依次執(zhí)行,后面需要調(diào)前面步驟的結(jié)果
async.waterfall(
[
function(done){
done(err, 結(jié)果) //將結(jié)果寫入result
},
function(result, done){
//result即上一步寫入的結(jié)果
done(err, 返回結(jié)果)
},
],
function(error, result){});
并行 async.parallel
某步出錯(cuò)不影響其他步驟執(zhí)行,最后結(jié)果中的error是第一個(gè)出現(xiàn)的error
async.parallel(
{
func1: function(done){
done(err, results)
},
func2: function(done){
done(err, results)
},
}, function(error, results){});
自動(dòng) async.auto
和series格式一樣,根據(jù)依賴關(guān)系自動(dòng)控制串行、并行
2.0版本前回調(diào)里的參數(shù)是(done, results),2.0及之后的版本統(tǒng)一把done作為最后一個(gè)參數(shù),即(results, done)
async.auto(
{
func1: function(done){
done(err, 要寫入func1的結(jié)果)
},
func2: ["func1", function(results, done){ //依賴func1
//results = {func1: xxx};
done(err, 返回結(jié)果)
}],
func3: ["func2", function(results, done){
}]
}, function(error, results){
results = {func1: xxx, func2: xxx, func3: xxx};
}
});
PART2
http://stackoverflow.com/questions/10390041/node-js-using-the-async-lib-async-foreach-with-object#
異步for循環(huán) async.forEach
async.forEach(list, function(item, done)
{
//操作item
done(); //通知for本循環(huán)完成
}, function(err){
//for之后執(zhí)行的函數(shù)
});
async.forEachOf
async.forEachOf(obj, function (value, key, callback) {})
//用法和上面forEach一樣,只是參數(shù)多了一個(gè)參數(shù),表示被遍歷value的index