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){
});
});
是否有这样的方法,如果function1如果booltest求值为true,不要移动到下一个输出"2"的函数?
如果你用true作为错误参数回调,那么流将停止,所以基本上
if (booltest)
callback(null, 'one');
else
callback(true);
应该
我认为你正在寻找的函数是async.detect not map.
从https://github.com/caolan/async#检测
示例代码detect(arr, iterator, callback)
返回arr中第一个通过异步真值测试的值。的并行应用迭代器,即第一个返回的迭代器True将使用该结果触发detect回调。这意味着Result可能不是原始arr中的第一项(按顺序)通过测试。
async.detect(['file1','file2','file3'], fs.exists, function(result){
// result now equals the first file in the list that exists
});
您可以将它与您的booltest一起使用以获得您想要的结果。
为了符合逻辑,您可以将error
重命名为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);
}
我传递一个对象来区分错误和功能。它看起来像:
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
}
}
后:
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
}
}
});