问题描述
我仍在尝试弄清楚如何在递归 AJAX 调用中使用 jQuery 延迟对象.我有这样的代码
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
}
这是 JSFiddle http://jsfiddle.net/petrabarus/BHswy/
Here's the JSFiddle http://jsfiddle.net/petrabarus/BHswy/
我知道如何在单个 AJAX 调用中使用 promise,但我不知道如何在递归 AJAX 调用中使用它.我想以类似于下面的方式调用 requestAll
函数
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);
});
我该怎么做?
推荐答案
如果您想使用 Promise,则不应使用 success
参数.相反,您想要返回
一个promise,并且您想要使用then
将promise的结果转换为不同的东西,甚至可能是另一个promise.
You should not use the success
parameter if you want to work with promises. Instead, you want to return
a promise, and you want to use then
to transform the results of a promise into something different, possibly even another promise.
function request(page) {
…
// return the AJAX promise
return $.ajax({
url: '/echo/json/',
method: 'POST',
dataType: 'json',
data: {
delay: 1,
json: JSON.stringify(ret)
}
});
}
function requestOddsFrom(page, items) {
return request(page).then(function(data){
if (data.currentPage > data.totalPage) {
return items;
} else {
var filtered = data.items.filter(function(el){ return el%2 == 1; });
return requestOddsFrom(data.currentPage + 1, items.concat(filtered));
}
});
}
function requestAll(){
return requestOddsFrom(1, []);
}
requestAll().then(function(items) {
console.dir(items);
});
这篇关于jQuery 递归 AJAX 调用承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!