node.js的最佳控制流模块是什么?

时间:2011-08-05 10:00:56

标签: asynchronous node.js control-flow

我使用了caolan's async module这是非常好的,但是跟踪错误以及为控制流传递数据的方式不同会导致开发有时非常困难。

我想知道是否有更好的选择,或者目前在生产环境中使用的是什么。

感谢阅读。

3 个答案:

答案 0 :(得分:17)

我也使用异步。为了帮助跟踪错误,建议您为函数命名,而不是加载匿名函数:

async.series([
  function doSomething() {...},
  function doSomethingElse() {...},
  function finish() {...}
]);

这样您就可以在堆栈跟踪中获得更多有用的信息。

答案 1 :(得分:4)

  

...但是跟踪错误以及为控制流传递数据的方式不同会导致开发有时非常困难。

我最近创建了一个名为“wait.for”的简单抽象来在同步模式下调用异步函数(基于Fibers):https://github.com/luciotato/waitfor

使用wait.for,你可以在仍然调用异步函数时使用'try / catch',并保持函数范围(不需要闭包)。例如:

function inAFiber(param){
  try{
     var data= wait.for(fs.readFile,'someFile'); //async function
     var result = wait.for(doSomethingElse,data,param); //another async function
     otherFunction(result);
  }
  catch(e) {
     //here you catch if some of the "waited.for" 
     // async functions returned "err" in callback
     // or if otherFunction throws
};

请参阅https://github.com/luciotato/waitfor

上的示例

答案 2 :(得分:-1)

有时很难将所有函数放在数组中。当你有一个对象数组并希望为每个对象做一些事情时,我会使用类似下面的例子。

请参阅:http://coppieters.blogspot.be/2013/03/iterator-for-async-nodejs-operations.html

 var list = [1, 2, 3, 4, 5];
 var sum = 0;

 Application.each(list, function forEachNumber(done) { 
   sum += this; 

   // next statement most often called as callback in an async operation
   // file, network or database stuff

   done(); // pass an error if something went wrong and automatically end here

 }, function whenDone(err) { 
   if (err) 
     console.log("error: " + err);
   else
     console.log("sum = " + sum); 

});

我命名函数,因为它更容易调试(并且更容易阅读)

相关问题