I want to use JavaScript asynchronous, as it was intended. I want to assign the recieved data/objects to as many variables as I'll need (DataModel01, DataModel02, DataModel03 and so on). The idea is that my need for API data change all the time, and I want to only have to define once where to get the data (API endpoint), and in what local variable/object to store it.
The way I'm doing it, it returns the object with recieved data from the fetchDataJSON() function. However, how do I make the return wait for the Ajax to finish? I've tried several things, including timers and callbacks, and nothing works at all.
I saw the other questions regarding ajax and async, and generally it was suggested to use callbacks. So I believe I might be offtrack, but I need a hand to figure out a way to deal with this gracefully. Do I really need to mess with timers and ugly solutions like that?
function fetchDataJSON(endpointUrl) {
var returnObj = [];
// Ajax call
$.ajax({
type: "GET",
url: endpointUrl,
dataType: 'json',
async: true,
success: updateData,
error: handleError
});
function updateData(data) {
returnObj = data;
}
function handleError(XHR, message, error) {
console.log("Failed XHR");
}
return returnObj; // Return JSON object
}
var DataModel01 = fetchDataJSON( "http://mydata.com/endpoint/sweetjson" );
var DataModel02 = fetchDataJSON( "http://mydata.com/endpoint/somethingelse" );
EDIT: I found a working solution now, yihar. I've marked the answer by Karman as accepted, as it was the one closest to the solution. My final solution, which was also inspired by a coworker, is as follows:
var DataModel01 = [];
var DataModel02 = [];
function fetchDataJSON(endpointUrl, callbackWhenDone) {
// Ajax call
$.ajax({
type: "GET",
url: endpointUrl,
dataType: 'json',
async: true,
success: updateData,
error: handleError
});
function updateData(data) {
callbackWhenDone(data);
}
function handleError(XHR, message, error) {
console.log("Failed XHR");
}
}
fetchDataJSON(
"http://mydata.com/endpoint/sweetjson",
function(newData) { DataModel01 = newData; }
);
fetchDataJSON(
"http://mydata.com/endpoint/somethingelse",
function(newData) { DataModel02 = newData; }
);