2

This is obviously an extremely simplified code snippet, but my code base is being held up with something that this example is set to mimic.

When I try to log the current for-loop index from within an async.waterfall function, I get 2. 2 is the number of total elements in my array, but of course the indices should be 0 and 1. I've effectively used async.MAP within a for-loop in the past, so I'm not sure why this async function is not working. Thanks for any help with this matter or on the topic of nesting async-library functions.

var objects = [
    {objectName: "hello",
        objectPurposes: ["demo"]},
    {objectName: "goodbye",
        objectPurposes: ["demo", "fun"]}];

for (var i=0; i<objects.length; i++){
    async.waterfall([
        function(callback){
            console.log(i);
        }
    ])
}
jaja
  • 127
  • 10
  • [async-waterfall](https://github.com/caolan/async#waterfalltasks-callback) accepts an array as first param, which will be your objects array, to iterate it over length of array. – Ravi Dec 24 '14 at 07:01
  • the first param of async-waterfall is the array of tasks, isn't it? – jaja Dec 24 '14 at 07:06
  • I think Ravi meant `async.forEach`. – icktoofay Dec 26 '14 at 01:48

1 Answers1

1

Well,the value of i would have changed by the time the async.waterfall completes its processing.If you want to retain the value of i,you could wrap it around a IIFE.

var objects = [{
    objectName: "hello",
    objectPurposes: ["demo"]
}, {
    objectName: "goodbye",
    objectPurposes: ["demo", "fun"]
}];

for (var i = 0; i < objects.length; i++) {
    (function(i) {
        async.waterfall([
            function(callback) {
                console.log(i);
            }
        ])
    })(i);
};

I would much rather use obj.shift() and wrap the async.waterfull under a recursive function for such a purpose though. http://book.mixu.net/node/ch7.html go through this,its really helpfull.

harryy000
  • 553
  • 3
  • 9