glasspill
glasspill

Reputation: 1300

nest async.waterfall in async.forEachSeries

I constructed this little simplified example to illustrate my problem with async:

var array = ["a", "b", "c", "d"];

async.forEachSeries(array, function(entry, callback){
    console.log(entry);

    async.waterfall([
       function(cb){
           console.log("step 1");
           cb(null,  "x");
       },
       function(param, cb){
           setTimeout(function(){console.log(param, "step 2");}, 1000);
           cb(null, "xx");
       },
       function(param, cb){
           console.log(param, "step 3");
           cb("xxx");
       }

    ], function(result, err){
        console.log(result, "waterfall done");
        callback();
    });

}, function(err){
    if(err) console.log("ERROR: "+ err);
});

The output of this is

    a
    step 1
    step 3 xx
    end xxx
    b
    step 1
    step 3 xx
    end xxx
    c
    step 1
    step 3 xx
    end xxx
    d
    step 1
    step 3 xx
    end xxx
    step 2 x
    step 2 x
    step 2 x
    step 2 x

How can I make sure the functions in the waterfall wait for the previous one to finish ?

Thank you

Upvotes: 0

Views: 323

Answers (1)

plalx
plalx

Reputation: 43718

I believe that you would have to put cb(null, "xx"); inside the setTimeout callback for step #2.

setTimeout(function() {
    console.log(param, "step 2"); 
    cb(null, "xx"); 
}, 1000);

Upvotes: 2

Related Questions