从延迟的ajax调用返回数据

时间:2015-07-31 09:44:29

标签: 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) {
  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()时,为什么数据不会从$.when( getApi(cookieName, cookieUrl) )返回?

1 个答案:

答案 0 :(得分:2)

getApiLocalStorage没有return语句,因此它将始终返回undefined。将其传递给JSON.parse()将引发异常。这会在函数到达console.log行之前中止该函数。

Promise可以更容易地将回调传递给异步函数。

Promise可以在调用异步函数后将回调传递给异步函数。

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

相关问题