I am trying to write a code which can determine if static data exists in localstorage than dont call ajax method to get data from server otherwise it should call ajax api and store the result in localstorage and return the data to its calling method.
here is my code:
staticService = function (key) {
return $.ajax({
type: 'GET',
url: "xxxxx.ashx/" + key,
dataType: "json",
success: function(result){
store.save(key, result);
}
});
}
var getFromStore = function (key)
{
if (key) {
var result = store.fetch(key);
if (!result) {
staticService(key);
}
return result;
}
}
var staticdata = {
gender: [{value:"M",text:"Male"}, {value:"F",text:"Female"}],
maritalStatus: getFromStore('availableMaritalStatus')
};
Problem: ajax calls are asynch and whenever I pass those keys which are not in store it return null, however it goes for ajax call and stores data in localStorage. I need somthing like
{
check list from store if exists return the list otherwise call ajax, get the list, store it in localStorage and return to user but without blocking UI
}
How can I accomplish this by changing my code? what is the best practice to do it?
EDIT: how to change staticdata variable logic so that i get staticdata.maritalStatus a valid data instead of null. I am loading static data on application load. If i try calling getFromStore number of times I dont know when will i reciev data from server as this will be invoking numerous susccess callbacks. I want static data to be called when all of the static services returned data successfully.