-1

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) )?

StudioTime
  • 22,603
  • 38
  • 120
  • 207

1 Answers1

2

getApiLocalStorage doesn't have a return statement so it will always return undefined. Passing that to JSON.parse() will throw an exception. That aborts the function before it reaches the console.log line.

Promises make it easier to pass callbacks to asynchronous functions.

Promises make it possible to pass callbacks to asynchronous functions after the asynchronous function has been called.

Promises do not make asynchronous functions synchronous. They do not allow you to return the final result before you have captured that result.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335