Async
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with Node.js and installable via npm install --save async, it can also be used directly in the browser.
在寫Node.js代碼的時候闯狱,由于Node.js的異步編程特性戏售,我們經(jīng)常會嵌套多個函數(shù)乏梁,導致代碼臃腫颂跨、維護性差:
func1() {
func2() {
func3() {
func4(){
...
}
}
}
}
Async正是解決了這個問題缰冤。
Async官網(wǎng): http://caolan.github.io/async/
Async實例
async.map(['file1','file2','file3'], fs.stat, function(err, results) {
// results is now an array of stats for each file
});
async.filter(['file1','file2','file3'], function(filePath, callback) {
fs.access(filePath, function(err) {
callback(null, !err)
});
}, function(err, results) {
// results now equals an array of the existing files
});
async.parallel([
function(callback) { ... },
function(callback) { ... }
], function(err, results) {
// optional callback
});
async.series([
function(callback) { ... },
function(callback) { ... }
]);
Async的幾種方式
1.series - 串行執(zhí)行
series(tasks, callbackopt)
串行執(zhí)行幾個函數(shù)犬缨,第一個參數(shù)既可以是Array,也可以是Object锋谐。
函數(shù)1執(zhí)行完后遍尺,不能將參數(shù)傳到函數(shù)2;故如果需要傳遞參數(shù)涮拗,不能用series乾戏,應(yīng)用waterfall。
在執(zhí)行函數(shù)過程中三热,一旦出現(xiàn)錯誤鼓择,將中斷;后續(xù)的函數(shù)將不再執(zhí)行就漾。
更詳細的資料呐能,請進入官網(wǎng): http://caolan.github.io/async/docs.html#series
async.series({
one: function(callback){
callback(null, 1);
},
two: function(callback){
callback(null, 2);
}
},function(err, results) {
console.log(results);
});
2.waterfall - 串行執(zhí)行,并傳參數(shù)
waterfall(tasks, callbackopt)
第一個參數(shù)必須是Array抑堡,它可以將參數(shù)傳遞到下一個函數(shù)摆出。
和series函數(shù)一樣,在執(zhí)行函數(shù)過程中首妖,一旦出現(xiàn)錯誤偎漫,將中斷;后續(xù)的函數(shù)將不再執(zhí)行有缆。
更詳細的資料象踊,請進入官網(wǎng):http://caolan.github.io/async/docs.html#waterfall
async.waterfall([
function(callback) {
callback(null, 'one', 'two');
},
function(arg1, arg2, callback) {
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
},
function(arg1, callback) {
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
3.parallel - 并行執(zhí)行
parallel(tasks, callbackopt)
顧名思義,就是各任務(wù)同時執(zhí)行棚壁,后面聲明的task不需要等待前面task結(jié)束杯矩,而是立即執(zhí)行。
需要注意的是袖外,最后的callback得到的參數(shù)史隆,是聲明中的最后一個函數(shù)傳入的,而不是最后執(zhí)行的函數(shù)曼验。
更詳細的資料泌射,請進入官網(wǎng):http://caolan.github.io/async/docs.html#parallel
async.parallel([
function(callback) {
setTimeout(function() {
callback(null, 'one');
}, 200);
},
function(callback) {
setTimeout(function() {
callback(null, 'two');
}, 100);
}
],
// optional callback
function(err, results) {
// the results array will equal ['one','two'] even though
// the second function had a shorter timeout.
});
4.parallelLimit - 并行執(zhí)行头镊,限制數(shù)量
parallelLimit(tasks, limit, callbackopt)
parallelLimit函數(shù)和parallel類似,只是多了一個參數(shù)limit魄幕。其作用是只能同時并發(fā)一定數(shù)量,而不是無限制并發(fā)
參考資料
[1] nodejs之a(chǎn)sync異步編程
[2] async官網(wǎng)