AnsweredAssumed Answered

Async Http request challenge

Question asked by franklin.alexander on Apr 27, 2018

I am trying to write an async http request to pull data from a json url, then do some things with it in order to run queries and finally, render the data to a graphics layer. Basically I need to create three variables with the json data, but two of the variables are dependent on the first, so I need them to wait til the first is created before passing them to another function. I cannot use fetch(), or async/await because they are not supported by IE , I have to go old school. My problem is that I am getting a 'function not defined' error before the .then(). This is telling me that the script is not waiting for the function to resolve before continuing on, but I am not sure what I need to do force the javascript to resolve the httpGetAsync function before continuing. Here is the relevant code: 


var searchrequest = "widgets/GopherTortoiseQuery/GTconn.php";
            if (tortoiseLayer == null) {
                var xhr = new XMLHttpRequest();
                function httpGetAsync(url) {
          "GET", searchrequest, true);
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState == 4 && xhr.status == 200){
                            JSONdata = eval("("+xhr.responseText+")");
                            console.log("JSONdata ", JSONdata);
                            return JSONdata;

                //tries to execute .then before httpGetAsync gets resolved
                httpGetAsync(searchrequest).then(function(JSONdata) { //error here
                    tortoiseLayer = JSONdata.Sightings;
                    console.log("now do something else");
                    return tortoiseLayer;


I need to chain two more .then functions and am pretty certain that once I get the first function to fully resolve I can go ahead and chain the remaining function without issue. I did try doing this using callbacks, but honestly with four functions to chain together it was getting to complicated! :-) I know there has to be a better way! 


thanks for any ideas!