从延迟ajax调用返回数据

Returning data from a deferred ajax call

本文关键字:返回 数据 调用 ajax 延迟      更新时间:2023-09-26

我试图从异步调用返回数据,但没有得到任何返回。

下面的代码被注释以进一步解释:

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) )返回数据?

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

Promises使得向异步函数传递回调更容易。

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

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