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

后端 未结 3 1595
醉梦人生
醉梦人生 2021-02-18 22:43

I\'ve used caolan\'s async module which is very good, however tracking errors and the varying way of passing data through for control flow causes development to sometimes be ver

相关标签:
3条回答
  • 2021-02-18 22:59

    ...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

    0 讨论(0)
  • 2021-02-18 22:59

    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)

    0 讨论(0)
  • 2021-02-18 23:14

    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.

    0 讨论(0)
提交回复
热议问题