有条件地调用节点中的asynchronousfunction

我有下面的示例代码 – 第一部分可以导致asynchronous调用或不 – 应该继续。 我不能把其余的代码放在asynchronouscallback中,因为当条件为假时需要运行。 那么如何做到这一点?

if(condition) { someAsyncRequest(function(error, result)) { //do something then continue } } //do this next whether condition is true or not 

我认为把代码放在函数中可能是在上面的asynchronous调用中或者在其他调用中调用该函数的方式,如果条件是错误的 – 但是有没有其他方式不需要我打破它的function?

只要声明一些其他函数,只要你需要它就可以运行:

 var otherFunc = function() { //do this next whether condition is true or not } if(condition) { someAsyncRequest(function(error, result)) { //do something then continue otherFunc(); } } else { otherFunc(); } 

我在Node中经常使用的库是Async( https://github.com/caolan/async )。 最后我检查了这也支持浏览器,所以你应该能够在你的发行版中使用npm / concat / minify。 如果你在服务器端使用这个,只有你应该考虑https://github.com/continuationlabs/insync ,这是一个稍微改进了的Async版本,删除了一些浏览器支持。

我在使用条件asynchronous调用时使用的一种常见模式是用我想要使用的函数填充数组,并将其传递给async.waterfall。

我在下面包含了一个例子。

 var tasks = []; if (conditionOne) { tasks.push(functionOne); } if (conditionTwo) { tasks.push(functionTwo); } if (conditionThree) { tasks.push(functionThree); } async.waterfall(tasks, function (err, result) { // do something with the result. // if any functions in the task throws an error, this function is // immediately called with err == <that error> }); var functionOne = function(callback) { // do something // callback(null, some_result); }; var functionTwo = function(previousResult, callback) { // do something with previous result if needed // callback(null, previousResult, some_result); }; var functionThree = function(previousResult, callback) { // do something with previous result if needed // callback(null, some_result); }; 

当然你可以用promise来代替。 无论哪种情况,我都喜欢避免使用asynchronous或promise来嵌套callback。

你可以通过不使用嵌套callback来避免的一些事情是variables碰撞,提升错误,向右“前进”,难以阅读代码等等。

只是另一种做法,这就是我抽象的模式。 可能有一些图书馆(承诺?)处理同样的事情。

 function conditional(condition, conditional_fun, callback) { if(condition) return conditional_fun(callback); return callback(); } 

然后在代码,你可以写

 conditional(something === undefined, function(callback) { fetch_that_something_async(function() { callback(); }); }, function() { /// ... This is where your code would continue }); 

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

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

 (go (when condition (<! (someAsyncRequest))) (otherCodeToHappenWhetherConditionIsTrueOrNot)) 

注意会导致主体asynchronous运行的gomacros,而<! 函数将阻塞,直到asynchronous函数将返回。 由于<! 函数在when条件内,只有条件为真时才会阻塞。