这是我想要实现的示意图:
function loadLotsofSomething() {
for (var i=0;i<1000;i++) {
results.push(loadOneSomething(i))
}
$.when.apply(this,results).done(function() {
for (var i = 0; i < arguments.length; i++) {
//get doSomehting(data) instead of data here
}
}
}
function loadOneSomething(i) {
return $.ajax({
async : true,
url: url,
success: function(data){
return doSomething(data);
}
});
}
function doSomething (x) {
return x;
}
我希望success
函数在done
函数之前执行,因为在循环遍历所有调用之前修改从 ajax 调用获得的数据更简单。
就我而言,无论我在success
函数中放入什么,我总是在done
函数中获取原始数据。
欢迎任何帮助!
你想使用链接(就像承诺一样(。根本不要使用success
;相反,请使用 then
并返回其结果:
function loadOneSomething(i) {
return $.ajax({
async : true,
url: url
}).then(function(data){
return doSomething(data);
});
}
这样,loadOneSomething
返回的承诺是来自then
的承诺,而不是来自$.ajax
的承诺,其解析值是你从then
返回的。
更多: $.ajax
中的 jqXHR 条目 , deferred.then
.