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

        }
    }
1
  • 1
    Use this.responseText instead of xmlhttp2.responseText, which has the loop scope problem Commented Feb 26, 2015 at 22:23

1 Answer 1

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.