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() {

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?


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){
        function() { return count <= Config.TotalFiles; },
            $this.CreateJSONFile(count, function() {
        }, function(){
           //This function is the final callback
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download