I'm still trying to figure out how to use jQuery deferred object in recursive AJAX call. I have a code like this
function request(page, items){
//building the AJAX return value for JSFiddle dummy AJAX endpoint
var ret = {
totalPage: 10,
currentPage: page,
items: []
};
for (var i = page; i < (page + 5); i++){
ret.items.push(i);
}
//calling the AJAX
$.ajax({
url: '/echo/json/',
method: 'POST',
dataType: 'json',
data: {
delay: 1,
json: JSON.stringify(ret)
},
success: function(data){
if (data.currentPage <= data.totalPage){
var filtered = data.items.filter(function(el){
return el % 2 == 1;
});
var newitems = items.concat(filtered);
console.dir(newitems);
request(data.currentPage + 1, newitems);
} else {
console.dir(items);
//resolve all item
}
}
});
}
function requestAll(){
request(1, []);
//should return a promise tha contains all items
}
Here's the JSFiddle http://jsfiddle.net/petrabarus/BHswy/
I know how to use promise in single AJAX call, but I have no idea how to use it in a recursive AJAX call. I want to call the requestAll
function in a way similar like below
var promise = requestAll();
promise.done(function(items){
console.dir(items);
});
How can I do this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…