1

I am making an async API call from inside a for loop in JavaScript and I am stuck on how to understand the result. This code is making the right calls to the API (I know this from looking at fiddler).

However when the reslts come back and I print the results at console.log(translation), I only see the result from the last API call.

I know this is an async problem but how best should I address the incoming response from 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();

        }
    }
tsurti
  • 17
  • 4
  • 1
    Use `this.responseText` instead of `xmlhttp2.responseText`, which has the [loop scope problem](http://stackoverflow.com/q/750486/1048572) – Bergi Feb 26 '15 at 22:23

1 Answers1

1

Figured it out. Closures 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);
    }
tsurti
  • 17
  • 4