Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS async.Whilst

var count = 0;

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

is there a way for the first function to pass the variable to the second function to be processed. For example:

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) {
    }
);
like image 377
samol Avatar asked Mar 03 '26 03:03

samol


1 Answers

Add a new scope to the whole async.whilst call, and make data a local variable of that scope:

(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) {
        }
    );
})();
like image 127
noseratio Avatar answered Mar 05 '26 21:03

noseratio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!