Asyncjs:绕过瀑布链中的函数

我想用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){ } ]); 

你知道一个正确的方法做这个没有放:

 if(!myBool){ return next(); } 

在我想绕过的function。

谢谢 !

另一种可能是:

 var tasks = [f1]; if(myBool){ tasks.push(f2); } tasks.push(f3); async.waterfall(tasks, function(err, result){ }); 

其中f1f2f3是你的function。

除此之外,你最好明确地做,避免让你的代码过于复杂,简单通常更好

更新:

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

我认为这应该工作:

 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 ) 

asynchronous的创build者推荐在github回购( https://github.com/caolan/async/pull/85

使用if-async模块,你的代码如下所示:

 var async = require('async') var ifAsync = require('if-async') async.waterfall([ foo, ifAsync(p1).then(c1).else(c2), bar ], function(err) {}) 

为完整的例子看看这里: https : //github.com/kessler/if-async#example-2-using-with-asyncjs-waterfall

我迟到了,但async-if-else可能会帮助你。

示例代码

  var async = require('async-if-else')(require('async')); function emailExists(user, callback) { user.find(user.email, function(err, dbUser){ if (err) return callback(error); if(!dbUser) return callback(null, false); // does not exist, predicate will be false callback(null, true); }); } function updateAccount(user, callback) { user.update( ..., callback); } function importFromLegacyByEmail(user, callback) { remoteClient.get(user, callback); } async.waterfall([ async.constant({email: 'thiago@email.com', dogs: 2, money: 0, fun: 100 }), async.if(emailExists, updateAccount).else(importFromLegacyByEmail), sendEmail ], handler); 

我会build议使用clojurescript有一个真棒核心asynchronous库,使处理asynchronous调用生活超级简单。

在你的情况下,你会写这样的东西:

 (go (when-let [res1 (<! (asyncFunc1))] (<! (asyncFunc2 res1))) (<! (asyncFunc3))) 

注意会导致主体asynchronous运行的gomacros,而<! 函数将阻塞,直到asynchronous函数将返回。

代码将首先阻止第一个asynchronous函数。 然后,如果结果是真的,那么它将在块上运行第二个asynchronous函数。 最后,它会运行第三个asynchronous函数并阻止它。