1

I need to perform a series of actions on a variable, where the output of the previous action would be the input of the next one.

Also, there is a possibility that at each step the whole process aborts in case the input is not well formed.

I know this could be done with the callback functions, but I have so many steps it's turning into a mess.

Does anybody know of a good solution I could use to avoid this? Just a module, which helps perform actions sequentially? Or another technique?

Thank you!

Aerodynamika
  • 7,883
  • 16
  • 78
  • 137

2 Answers2

1

It sounds like async.waterfall might be what you're looking for.

As far as aborting early goes, async doesn't have an easy way to do this, but what I've generally done is call the callback with a "fake" Error instance and then in the final callback, I check for a "fake" Error vs real error (usually I tack on some property like 'err.abort = true;` and check for that).

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • You are my savior! Thank you so much, @mscdex. I've been fighting with it for 12 hours and what you suggested worked like magic! – Aerodynamika May 26 '14 at 11:36
1

If you use Async.js. You can use async.whilst or async.until

var count = 0;

async.whilst(
    function () { return count < 5; },
    function (callback) {
        count++;
        setTimeout(callback, 1000);
    },
    function (err) {
        // 5 seconds have passed
    }
);

the first function is used for conditional check. the second function is actually logic, you can save the result and reuse it as the new input.

Jake Lin
  • 11,146
  • 6
  • 29
  • 40