In my quest to leverage JavaScript asynchronously to its full potential, I am looking for a way to efficiently handle received data from API calls. My goal is to dynamically assign the data to multiple variables such as DataModel01, DataModel02, DataModel03, and so on. Given that my requirements for API data are constantly changing, I want a single place where I can specify the API endpoint and the local variable/object to store the fetched data.
Currently, the fetchDataJSON() function returns the object with the received data. However, I am faced with the challenge of making the return statement wait for the Ajax call to finish. Despite attempting various approaches like timers and callbacks, I have not been successful in synchronizing the return with the completion of the Ajax request.
After exploring similar questions on Ajax and asynchronous programming, it seems that using callbacks is the recommended approach. While I suspect that I may be missing something crucial, I am seeking guidance on how to elegantly handle this situation without resorting to cumbersome solutions like timers.
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 have finally arrived at a working solution, hooray! I have marked Karman's answer as accepted since it was closest to the solution. My ultimate implementation, which drew inspiration from a colleague, is outlined below:
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; }
);