我用的是草兰的辉煌Async.js 。我正在执行一系列功能。在第一个函数中,我有一个条件,应该跳过该系列的所有其余函数并直接转到最终回调:
async.series([
function one (next) {
if(!condition) {
// skip all the other functions and go to final callback
}
// do stuff
return next();
},
function two (next) {
// do stuff
return next();
},
function three (next) {
// do stuff
return next();
}
], function (err) {
// final callback stuff
});
因此,如果函数中不满足一个条件,则直接转到最终回调。
If any functions in the series pass an error to its callback, no more functions are run, and callback is immediately called with the value of the error.
但是抛出错误对我来说看起来并不是一个干净的方法。为了能够在最终回调中正确处理“真实”错误,我必须引入一个假错误......还有其他干净的方法吗?
最佳答案
目前我是如何解决这个问题的。我确实抛出了一个特定的错误来跳过本系列的其余部分,从最终回调中的一般错误处理中排除此特定错误:
async.series([
function one (next) {
if(!condition) {
return next('condition_not_met');
}
return next();
},
function two (next) {
// this isn't executed if condition isn't met in function one
return next();
}
], function (err) {
if (err && err !== 'condition_not_met') {
// general error handling
}
// do more stuff
});
如果这是 async.series 的使用方式,或者是否有更优雅的方式来处理我的场景,我仍然感兴趣。干杯。
关于node.js - Async.js 跳出系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28220279/