Я пытаюсь вернуть данные из асинхронного вызова, но ничего не получаю.Возврат данных из отложенного вызова 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))
?
Вы не можете возвращать данные из любого ajax или отложенного обратного вызова, никогда, даже если он синхронизирован –