I'm trying to return data from an asynchronous call but not getting anything returned.
Code below which is commented to explain further:
function displayBox() {
var data = JSON.parse(getApiLocalStorage('getApi')); // 1. get the data
console.log('data is '+data); // <-- never gets called
}
function getApiLocalStorage(cookieName, url) {
var cookieName = cookieName || 'getApi',
cookieUrl = url || 'https://s.apiUrl.com/75/f.json',
store = null;
if (store === null) { // if null, go get the data
$.when( getApi(cookieName, cookieUrl) ).then( // 2. it's not there so wait for the data to come through
function(data) {
console.log(data); // <-- when data comes back, this is ok
return data; // <-- this seems to do nothing
}
);
}
}
function getApi(cookieName, url, callback) {
var deferred = $.Deferred();
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: true,
success: function(jsonData) {
var data = JSON.stringify(jsonData);
deferred.resolve(data);
}
});
return deferred.promise();
}
displayBox(); // start the process
Question is, when displayBox()
is called, why is data not being returned from $.when( getApi(cookieName, cookieUrl) )
?