Javascript 从延迟的ajax调用返回数据

Javascript 从延迟的ajax调用返回数据,javascript,jquery,ajax,Javascript,Jquery,Ajax,我试图从异步调用返回数据,但没有返回任何内容 下面对其进行注释以进一步解释的代码: function displayBox() { var data = JSON.parse(getApiLocalStorage('getApi')); // 1. get the data console.log('data is '+data); // <-- never gets called } function getApiLocalStorage(cookieName, url) {

我试图从异步调用返回数据,但没有返回任何内容

下面对其进行注释以进一步解释的代码:

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
问题是,当调用displayBox时,为什么不从$返回数据。当getApicookieName、cookieUrl?getApiLocalStorage没有返回语句时,它总是返回未定义的数据。将其传递给JSON.parse将引发异常。在函数到达console.log行之前中止该函数

承诺使将回调传递给异步函数变得更容易

承诺使得在异步函数被调用后可以将回调传递给异步函数


承诺不会使异步函数同步。它们不允许您在捕获最终结果之前返回该结果。

您不能从任何ajax或延迟回调返回数据,永远不能,即使它是同步的