在nodejs中,有更好的devise模式来同步调用asynchronous函数吗?

例如,我想写一个testing用例,它需要跟踪一系列调用的状态。

我可以得到这样的东西:

async_fun(function () { // Do something ... async_fun(function () { // Do something ... async_fun(function () { // Do something ... // ... }); }); }); async_fun(); 

当我需要运行一个大的循环时,我可以做如下的尾recursion :

 function helper (mount) { async_fun(function (){ if (mount) return; // Do something ... helper(mount--); }); } helper(10000); 

但是,我听说V8引擎没有对尾部调用进行优化,所以可能会吃掉内存。 有没有更好的devise模式来完成这项任务?

PS:请没有第三个lib。 我想要一个本地解决scheme。

对于你的第二个例子,我build议使用事件。 如果您使用注册事件以及全局(或闭包)计数器,它将保持调用堆栈的增长,但实现相同的逻辑。 假设countDown方法做了一些asynchronous工作,只是通过这个asynchronous工作一个callback,发出下一个事件的行。

 var events = require("events"); function recursiveCountDown(someVariable) { var counter = someVariable; var eventEmitter = new events.EventEmitter();//create a new event object, so we can have lots of these running potentially without interfering with one another! var eventName = 'count'; function countDown() { someVariable--; console.log(someVariable); if(someVariable) eventEmitter.emit(eventName); } eventEmitter.on(eventName, countDown); eventEmitter.emit(eventName); } recursiveCountDown(1000); 

对于您的第一个问题,有几个stream量控制库可用。 说实话,你已经用一种比较恶毒的方式组织起来了。 你可以做一些组织的事情来使这个“更好”,但他们最终只能看起来更好。 没有办法避免这种逻辑stream动,从我的angular度来看,我更喜欢看到事情是如何执行的。 但是,这只是一个意见。 你可以看看一些stream量控制库,ASYNC似乎是标准的。 基本上,它允许的是让你展现你的函数,就好像它们是按照顺序执行一样,尽pipe在内部它们被包装和执行,就像你上面已经提到的那样。 我更喜欢以下成语:

 function doABunchOfAsyncWorkInSeries(arg, callbackToMainEventLoop) { var sharedByAll = 'OUTPUT: ' setTimeout(function(){ console.log(sharedByAll + arg); asyncFun2('a different string'); }, 1000); function asyncFun2(arg2) { setTimeout(function() { console.log(sharedByAll + arg2); asyncFun3('final string'); }, 2000); } function asyncFun3(arg3) { setTimeout(function(){ console.log(sharedByAll +arg3); callbackToMainEventLoop('FINISHED'); }, 3000); } } doABunchOfAsyncWorkInSeries('first string', function(arg) { console.log('The program is finished now. :' + arg); }); 

请注意,逻辑的stream程是基本相同的,但function是串联的。 所以很明显,一个人正在执行另一个,尽pipedoSomeWork ….函数可以是asynchronous的,而不影响逻辑stream程。 在你的例子中,你做了同样的事情,但是每个连续的函数在其closures中包含另一个函数…没有理由这样做。 这只是看起来更清洁。 再一次,如果你不介意库为你做这样的事情,为了简化你的语法,看看asynchronous。 但在内部,这是Async正在做的事情。 我真的很喜欢这个语法。