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

戏子无情 提交于 2019-12-03 11:30:54

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

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.

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);
}

I'm passing an object to differentiate between an error and just functionality. Which looks like:

function logAppStatus(status, cb){
  if(status == 'on'){
    console.log('app is on');
    cb(null, status);
  }
  else{
    cb({'status' : 'functionality', 'message': 'app is turned off'}) // <-- object 
  }
}

Later:

async.waterfall([
    getAppStatus,
    logAppStatus,
    checkStop
], function (error) {
    if (error) {
      if(error.status == 'error'){ // <-- if it's an actual error
        console.log(error.message);
      }
      else if(error.status == 'functionality'){ <-- if it's just functionality
        return
      }

    }
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!