处理异步功能

时间:2013-12-12 17:46:52

标签: javascript node.js asynchronous

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

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

它确实不起作用,因为,processSource需要一段时间才能完成,函数doesOtherStuff将使用不匹配的参数调用,例如sources[2]和{{1}的已处理信息1}}。

处理此问题的正确方法是什么?这些功能的设计是否存在固有的错误。 (processSource和doOtherStuff都是我的函数)。

4 个答案:

答案 0 :(得分:2)

代码的问题在于i不希望您期望它。

当循环完成时,函数级变量i具有sources.length的值。因此,当doOtherStuff运行时,内部函数会使用它。

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

答案 1 :(得分:1)

javascript风格可以帮到你:

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

答案 2 :(得分:0)

1)使用var代替int

2)您对)的电话中有一个多余的processSource

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

应该有用。

答案 3 :(得分:0)

尝试使用Caolan's async library - 这适用于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
});
相关问题