Javascript异步调用for循环内部

时间:2015-02-26 21:16:09

标签: javascript for-loop asynchronous google-chrome-extension

我正在使用JavaScript中的for循环内部进行异步API调用,而我仍然坚持如何理解结果。这段代码正在调用API(我从fiddler那里知道这一点)。

然而,当reslts返回并且我在console.log(翻译)打印结果时,我只看到上次API调用的结果。

我知道这是一个异步问题,但我应该如何最好地解决来自xmlhttp2的传入响应?

        for (var j = 0; j <= current; j++) {
        //some preprocessing                

            var xmlhttp2=new XMLHttpRequest();
            xmlhttp2.onreadystatechange=function()
            {
                if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
                {
                    var translation = xmlhttp2.responseText;
                    console.log(translation);
                }
            }                               

            var sendparam = "http://api.foo.do.stuff.etc";
            xmlhttp2.open("GET",sendparam,true);
            xmlhttp2.send();

        }
    }

1 个答案:

答案 0 :(得分:1)

想出来。关闭FTW

    for (var j = 0; j <= current; j++) {
    //some preprocessing                
        (function (j) {
        var xmlhttp2=new XMLHttpRequest();
        xmlhttp2.onreadystatechange=function()
        {
            if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
            {
                var translation = xmlhttp2.responseText;
                console.log(translation);
            }
        }                               

        var sendparam = "http://api.foo.do.stuff.etc";
        xmlhttp2.open("GET",sendparam,true);
        xmlhttp2.send();
        })(j);
    }