I have a problem, I have written a nice function that returns a dataset from a local JSON file on my server. I wish to use the returned data by setting this to a variable to I can pass it to other functions later however due to the asynchronous nature of AJAX my variable will always be set to undefined
as the variable is set before the dataset from my function is returned. I don't want to set my variable inside my fetchData
function, what is the best way to assign my variable value here whilst waiting for the fetchData
function. Should I return some kind of callback or does this need a promise of some kind or should I set 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);