Question

The popular node.js module async includes functions for collections and control flow which, with versions of some which can be operate in parallel or in series.

But among them I cannot find a way to construct a loop which operates in series.

I'm trying to do the same as this pseudocode:

forever {
    l = getline();

    if (l === undefined) {
        break;
    } else {
        doStuff(l);
    }
}
  • If I wanted all the calls to getLine() to be called in parallel I could use async.whilst.
  • If I wanted to iterate over an array rather than make something like a for or while loop I could use async.eachSeries.

What can I use to get the series behaviour in control flow rather than collection iteration?

Was it helpful?

Solution

async.whilst does execute its function serially like you need, so you can do something like this:

var l = getline();
async.whilst(
    function () { return l !== undefined; },
    function (callback) {
        doStuff(l);
        l = getline();
        callback(); // Check function isn't called again until callback is called
    },
    function (err) {
        // All done
    }
);

OTHER TIPS

If you want to execute loop in series like a synchronous code, you should use async.series or async.waterfall

series(tasks, [callback])

Run an array of functions in series, each one running once the previous function has completed. If any functions in the series pass an error to its callback, no more functions are run and the callback for the series is immediately called with the value of the error. Once the tasks have completed, the results are passed to the final callback as an array.

waterfall(tasks, [callback])

Runs an array of functions in series, each passing their results to the next in the array. However, if any of the functions pass an error to the callback, the next function is not executed and the main callback is immediately called with the error.

Waterfall chains callbacks to pass output of one as input of next, series just executes in series.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top