I'm trying to use AJAX (through jQuery) to return a bit of JSON from an API, and then store that JSON in localStorage as a string. Whenever the function runs, I want it to check localStorage for the key, and return that value if it exists. If it does not exist, then it should contact the API for the object, save it to localStorage, and then return it.
The problem that I'm having is this: the function NEVER returns the JSON object the first time (when it's not stored in localStorage). It has no problem saving it to localStorage, and it always pulls it from localStorage just fine, but even right after using the returned object in the previous line, the function won't return it. The console just says "undefined".
The code I'm using is below (edited slightly since the API is private):
window.get_company = function() {
var full = window.location.host;
var parts = full.split('.');
var subdomain = parts[0];
if ( localStorage.getItem("company_" + subdomain) === null ) {
$.getJSON("https://api.testingapp.com/subdomains?name=" + subdomain).then( function(data) {
localStorage.setItem("company_" + subdomain, JSON.stringify(data));
return JSON.stringify(data);
});
} else {
return localStorage.getItem("company_" + subdomain);
}
}
Thanks so much for your help!
.done()on$.getJSONwould execute the code inside of it only once the request was complete, but I guess that isn't the case. Can you help me understand then? I'm particularly confused about why thelocalStoragekey gets the value set bydatacorrectly, but thereturndoesn't. Like, if the value is being set inlocalStorage, shouldn't it be doing that before that same value is returned?