What is the best control flow module for node.js?

流过昼夜 提交于 2019-12-03 22:46:17

I use async as well. To help tracking errors it's recommended you name your functions, instead of having loads of anonymous functions:

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

This way you'll get more helpful information in stack traces.

...however tracking errors and the varying way of passing data through for control flow causes development to sometimes be very difficult.

I've recently created a simple abstraction named "wait.for" to call async functions in sync mode (based on Fibers): https://github.com/luciotato/waitfor

Using wait.for, you can use 'try/catch' while still calling async functions, and you keep function scope (no closures needed). Example:

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

see the examples at https://github.com/luciotato/waitfor

Sometimes it is hard to put all the functions in an array. When you have an array of objects and want to do something for each object, I use something like the example below.

read more in: 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); 

});

I name the functions, because it is easier to debug (and easier to read)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!