Search code examples
node.jsnode-async

node Async push loop


I have a async function I want to execute for i in a range. I tried this :

var async = require('async');

function main(a, b){

    var funcs = [];

    for(var i=a; i<=b; i++){
        var txt = "func "+i;

        funcs.push(function(callback){
            console.log(i);
            console.log(txt);
            callback(null, null);
        });
    }

    async.parallelLimit(funcs, 10, function(){
        console.log("done");
    });

}

main(1,5);

and the output is :

6
func 5
6
func 5
6
func 5
6
func 5
6
func 5
done

why i have not "func 6" ??? and btw I want 1 2 3 4 5 ...

Thanks


Solution

  • Your functions will be executed after loop is done. So after loop i will be equal 6, and txt will be equal func 5. Put content of your loop into closure to fix it:

    for(var i=a; i<=b; i++){
        (function(i) {
            var txt = "func "+i;
    
            funcs.push(function(callback){
                console.log(i);
                console.log(txt);
                callback(null, null);
            });
        })(i);
    }
    

    PS In ECMAScript 6 (upcoming specification of JavaScript) there are let variables which resolve this problem.