Having an issue here! I've created a function to retrieve data from a local JSON file on my server. The problem is that the data is returned asynchronously, so when I try to set it to a variable for later use, it always ends up being undefined
. I don't want to set the variable inside the fetchData function itself. What would be the best approach to assign the variable value while waiting for the fetchData function? Do I need to implement some kind of callback, or perhaps use a promise? Should I consider setting the async argument of window.XMLHttpRequest.open
to false
?
'use strict';
function fetchData() {
var prodData;
if (window.XMLHttpRequest) {
prodData = new XMLHttpRequest();
prodData.overrideMimeType('application/json');
prodData.open('GET', 'products.json', true);
prodData.send();
prodData.onreadystatechange = function () {
if (prodData.readyState === 4 && prodData.status === 200) {
return prodData.responseText;
} else {
return false;
}
};
}
}
var myData = fetchData();
// later I shall use this data like so...
doSomethingWithMyData(myData);