处理asynchronousfunction

我刚刚开始用JS和Node编程,而且我还没有习惯于asynchronous的东西。 基本上,我有以下代码:

for (var i=0, len=sources.length; i<len; i++) { processSource(sources[i], function(info) { doesOtherStuff(sources[i], info); }); } 

它并没有真正的工作,因为,当processSource需要一段时间才能完成,函数doesOtherStuff被调用,具有不匹配的参数,如sources[2]sources[0]的处理信息。

处理这个问题的正确方法是什么? 这些function的devise是否有内在的错误? (processSource和doesOtherStuff都是我的function)。

代码的问题是, i不想要你期望的事实。

当循环完成时,函数级variablesi的值为sources.length。 所以当这个内部函数使用的时候,这个运行的是什么呢?

 for (var i=0, len=sources.length; i<len; i++) { (function(i) { processSource(sources[i], function(info) { doesOtherStuff(sources[i], info); }); })(i); } 

JavaScript风格可以帮助你:

 sources.forEach(function (e) { processSource(e, function(info) { doesOtherStuff(e, info); }); } 

尝试使用Caolan的asynchronous库 – 这适用于Node和浏览器。 然后你可以做这样的事情:

 async.map(sources, function (item, callback) { // Do your actions on each item here processSource(item, function (info) { var result = doOtherStuff(item, info); // Send callback so the next item can be processed callback(null, result); }); }, function (err, results) { // Handle the processed results here }); 

1)使用var而不是int

2)你有一个多余的)在你的调用processSource

 processSource(sources[i], function(info) /* No 2nd ')' here */ { doesOtherStuff(sources[i], info); }); 

应该pipe用。