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