Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to stop execution of next function of series with async in nodejs?

  async.map(list, function(object, callback) {
    async.series([
      function(callback) {
        console.log("1");

        var booltest = false;
        // assuming some logic is performed that may or may not change booltest
        if(booltest) {
            // finish this current function, move on to next function in series
        } else {
           // stop here and just die, dont move on to the next function in the series
        }

        callback(null, 'one');
      },
      function(callback) {
        console.log("2");
        callback(null, 'two');
      }
    ],
    function(err, done){
    });
  });

Is there some way such that if function1 if booltest evaluates to true, don't move on to the next function that outputs "2"?

like image 992
Rolando Avatar asked May 07 '13 15:05

Rolando


3 Answers

The flow will stop if you callback with true as your error argument, so basically

if (booltest)
     callback(null, 'one');
else
     callback(true);

Should work

like image 115
drinchev Avatar answered Oct 26 '22 07:10

drinchev


I think the function you are looking for is async.detect not map.

from https://github.com/caolan/async#detect

detect(arr, iterator, callback)

Returns the first value in arr that passes an async truth test. The iterator is applied in parallel, meaning the first iterator to return true will fire the detect callback with that result. That means the result might not be the first item in the original arr (in terms of order) that passes the test.

example code

async.detect(['file1','file2','file3'], fs.exists, function(result){
    // result now equals the first file in the list that exists
});

You could use that with your booltest to get the result you want.

like image 32
mikkom Avatar answered Oct 26 '22 05:10

mikkom


To make it logical, you could just rename error to something like errorOrStop:

var test = [1,2,3];

test.forEach( function(value) {
    async.series([
        function(callback){ something1(i, callback) },
        function(callback){ something2(i, callback) }
    ],
    function(errorOrStop) {
        if (errorOrStop) {
            if (errorOrStop instanceof Error) throw errorOrStop;
            else return;  // stops async for this index of `test`
        }
        console.log("done!");
    });
});

function something1(i, callback) {
    var stop = i<2;
    callback(stop);
}

function something2(i, callback) {
    var error = (i>2) ? new Error("poof") : null;
    callback(error);
}
like image 26
Steven Vachon Avatar answered Oct 26 '22 05:10

Steven Vachon