1

whenever I try to execute this request asynchronously the variable never resolves in time to return the value. Is this because of how I am calling it with an IIFE?

It worked asynchronously before I put it in the IIFE, and when within only works synchronously. I know synchronous requests are the devil but without this request returning data the whole page is dead anyway. I will set a timeout function in there next but I want to focus on the initial question. Thanks for your help!

var goldPrice = (function () {
var price;
  //removed goldDataUrl with API info
    var request = new XMLHttpRequest();
    request.open('GET', goldDataUrl, false);
    request.onload = function() {
        if (request.status >= 200 && request.status < 400) {
            // Success!
            price = JSON.parse(request.responseText).dataset.data[0][1];
        }
        else {
            // We reached our target server, but it returned an error
        }
    }
    request.onerror = function () {
        // There was a connection error of some sort
    };
    request.send();
return price;})();
D. Cantatore
  • 187
  • 12
  • 3
    The issue isn't strictly with the IIFE, but that `return price;` will always be evaluated before `price = JSON.parse(...);` when the `request` is asynchronous (non-blocking / completing in its own time). A good explanation and summary of options can be found in: "[How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/)" – Jonathan Lonowski Sep 17 '16 at 05:54
  • 1
    You can return a `Promise` from `goldPrice` where the value of the resolved promise is set to `price` – guest271314 Sep 17 '16 at 05:57
  • I haven't used Promise yet but this could be a great time to start. It's too bad IE doesn't support it yet. I think this info explains and solves it. Thanks both of you. – D. Cantatore Sep 17 '16 at 06:04
  • `It's too bad IE doesn't support it yet` [MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise#See_also) has a link to a [polyfill](https://github.com/stefanpenner/es6-promise) - I haven't used that one myself - but it looks OK – Jaromanda X Sep 17 '16 at 06:18

0 Answers0