EyWN EyWN - 3 years ago 105
Node.js Question

NodeJs Use async with for loop download

I have this loop for download some files and it's work fine.

But the files are downloaded like "2,3,4,1,5" order and not "1,2,3,4,5".

I know how to do .each async and waterfall async but I don't know how to do for this loop.

Config.TotalFiles = 5;

for(i = 1; i <= Config.TotalFiles; i++) {
$this.CreateJSONFile(i, function() {
cls();
});
}


And when downloads are done I want to call my callback, I have tried this
if(id == Config.TotalFiles)
but it's doesn't work because the id isn't good.

How can I done an "async" process with this loop?

Thanks

Answer Source

You can use async.whilst for this:

Config.TotalFiles = 5;
var count = 1;

//pass your maincallback that you want to call after downloading of all files is complete.

var callMe = function(mainCallback){
    async.whilst(
        function() { return count <= Config.TotalFiles; },
        function(callback){
            $this.CreateJSONFile(count, function() {
                cls();
                count++;
                callback();
            });
        }, function(){
           //This function is the final callback
           mainCallback();
        })
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download