user2831512 user2831512 - 22 days ago 10
Node.js Question

use async.series or waterfall in a loop

I am just learning to use async and I want to do something like this:

var listOfArguments = [];
async.waterfall([
getTheListOfArguments,
function(callback) {
if (listOfArguments.lengh > 0) {
doSomething(listOfArguments.shift());
} else {
callback(null, listOfArguments);
}
}
], function(err, res) {
})


In fact I want getListOfArguments to read some list and keep it globally, then I want to loop over the doSomething function to get each element of the array as an input and move on to the next element only when it's done with the first (hence the use of async!), but this doesn't seem to work.

Can anyone help me please?

Answer

While i'm not quite sure what you are trying to achive, i believe the code you need might look more like this

var listOfArguments = [];

getTheListOfArguments(function(){
    // listOfArguments now contains some items, let's process it
    if(listOfArguments.length) doSomething();
});

function doSomething() {

    var item = listOfArguments.pop();

    // ... do your thing here

    // if we still have some items in the listOfArguments array doSomething again
    if(listOfArguments.length) return doSomething();

    // we are done, do something here
    console.log('Done');
}