使用Async,讓你的Node.js代碼更優(yōu)雅

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代碼的時(shí)候,由于Node.js的異步編程特性,我們經(jīng)常會(huì)嵌套多個(gè)函數(shù),導(dǎo)致代碼臃腫、維護(hù)性差:

func1() {
    func2() {
        func3() {
            func4(){
                ...
            }
        }
    }
}

Async正是解決了這個(gè)問(wèn)題。

Async官網(wǎng): http://caolan.github.io/async/


Async實(shí)例

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í)行幾個(gè)函數(shù),第一個(gè)參數(shù)既可以是Array,也可以是Object。

函數(shù)1執(zhí)行完后,不能將參數(shù)傳到函數(shù)2;故如果需要傳遞參數(shù),不能用series,應(yīng)用waterfall。

在執(zhí)行函數(shù)過(guò)程中,一旦出現(xiàn)錯(cuò)誤,將中斷;后續(xù)的函數(shù)將不再執(zhí)行。

更詳細(xì)的資料,請(qǐng)進(jìn)入官網(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)

第一個(gè)參數(shù)必須是Array,它可以將參數(shù)傳遞到下一個(gè)函數(shù)。

和series函數(shù)一樣,在執(zhí)行函數(shù)過(guò)程中,一旦出現(xiàn)錯(cuò)誤,將中斷;后續(xù)的函數(shù)將不再執(zhí)行。

更詳細(xì)的資料,請(qǐng)進(jìn)入官網(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ù)同時(shí)執(zhí)行,后面聲明的task不需要等待前面task結(jié)束,而是立即執(zhí)行。

需要注意的是,最后的callback得到的參數(shù),是聲明中的最后一個(gè)函數(shù)傳入的,而不是最后執(zhí)行的函數(shù)。

更詳細(xì)的資料,請(qǐng)進(jìn)入官網(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類似,只是多了一個(gè)參數(shù)limit。其作用是只能同時(shí)并發(fā)一定數(shù)量,而不是無(wú)限制并發(fā)


參考資料

[1] nodejs之a(chǎn)sync異步編程
[2] async官網(wǎng)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容