javascript中有許多可以統一收集異步回傳資料的方法,例如jQuery的$.when()

而node.js中也可以透過async module來達到一樣的目的

async github 裡面會有詳細的文件

npm安裝

npm install async

以讀取MySQL multiple query為例

var conn    = require('./routes/mysql'),
    async   = require('async')

async.parallel([
        function(callback){ conn.db.query("SELECT * FROM `table`", function(err, result){ callback(err, result);}); },
        function(callback){ conn.db.query("SELECT * FROM `table`", function(err, result){ callback(err, result);}); }
    ], function(err, result) {
        console.log(err);
        console.log(result);
});

另外也可以使用whilst執行大量的function

//用法
var count = 0;

async.whilst(
    function () { return count < 5; },
    function (callback) {
        count++;
        setTimeout(callback, 1000);
    },
    function (err) {
        // 5 seconds have passed
    }
);

以request為例

var request = require("request"),
    async   = require("async");

count = 0;
async.whilst(function () {
    return count < 3;
},
function (next) {
    request({
        uri: '',
    },function(error, response, body) {
        if(!error) {
            console.log(body);
            count++;
            next();
        }
    });
},
function (err) {
    //最後會執行,如果沒有錯誤,err會等於undefined
    console.log(err);
});
Categories: Node.js