NodeJS async.Whilst

时间:2014-02-19 23:28:15

标签: node.js asynchronous

var count = 0;

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

有没有办法让第一个函数将变量传递给第二个要处理的函数。例如:

async.whilst(
    // if EOF data will evaluate to false
    // otherwise, data will be an object
    function () { var data = processSomeDataSync(); return data },
    function (data, callback) {
        process(data)
    },
    function (err) {
    }
);

1 个答案:

答案 0 :(得分:5)

向整个async.whilst调用添加新范围,并使data成为该范围的局部变量:

(function() {
    var data = null;

    async.whilst(
        // if EOF data will evaluate to false
        // otherwise, data will be an object
        function () { 
            data = processSomeDataSync(); return data != null; 
        },
        function (callback) {
            process(data)
        },
        function (err) {
        }
    );
})();