man*_*tin 7 asynchronous waterfall callback node.js
我想从瀑布功能链跳转的功能与asyncjs在nodejs.
我的代码看起来像这样:
async.waterfall([
function(next){
if(myBool){
next(null);
}else{
// Bypass the 2nd function
}
},
// I want to bypass this method if myBool is false in the 1st function
function(next){
},
// Always called
function(next){
}
]);
Run Code Online (Sandbox Code Playgroud)
你知道一个正确的方法来做到这一点,而不是:
if(!myBool){
return next();
}
Run Code Online (Sandbox Code Playgroud)
在我想要绕过的功能中.
谢谢 !
我认为这应该有效:
var finalCallback = function(err, result){
if(err)
// handle error..
else
console.log('end! :D');
}
async.waterfall(
[
function step1(callback){
// stuff
callback(null, someData);
},
function step2(someData, callback){
if(skip_step_3)
finalCallback(null, someData);
else
callback(null, someData);
},
function step3(moreData, callback){
// more stuff
callback(null, moreData);
}
],
finalCallback
)
Run Code Online (Sandbox Code Playgroud)
async的创建者在github repo中推荐这个(https://github.com/caolan/async/pull/85)
另一种选择可能是:
var tasks = [f1];
if(myBool){
tasks.push(f2);
}
tasks.push(f3);
async.waterfall(tasks, function(err, result){
});
Run Code Online (Sandbox Code Playgroud)
在哪里f1,f2和,f3是你的功能.
除此之外,你最好明确地做它,避免使你的代码过于复杂,通常更好更简单
更新:
function f1(done){
if(myBool){
f2(done);
}else{
done();
}
}
function f2(done){
async.nextTick(function(){
// stuff
done();
});
}
async.waterfall([f1,f3],function(err,result){
// foo
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4513 次 |
| 最近记录: |