2011-08-05 42 views

回答

17

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

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

这样你会得到堆栈跟踪更多有用的信息。

+0

谢谢,这有帮助。你知道其他任何好的吗? –

+0

另一个我使用的是[步骤](https://github.com/creationix/step),这是相当不错的。我认为异步有更多的选择可能更适合不同的情况。 – evilcelery

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

}); 

我的名字的功能,因为它更容易调试(易读)

3

...但跟踪误差和的不同方式通过控制流量传递数据导致开发有时非常困难。

我最近创建了一个名为“wait.for”一个简单的抽象来调用同步模式异步功能(基于纤维):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

+0

优雅。纤维牺牲了一点便携性。但这是最可读的[解决方案]之一(https://github.com/joyent/node/wiki/modules#user-content-wiki-async-flow)我见过,不需要预处理器。做得好! – joeytwiddle

相关问题