我当前正在使用jQuery.when异步执行不同的请求。 问题在于,似乎jQuery。何时等待每个调用完成,然后再运行下一个。
第五次调用等待大约需要几秒钟才能返回,例如当单独执行时需要大约一秒钟来处理。
这是我的通话时间:
jQuery.when(search_engine.fetchBucketOne(), search_engine.fetchBucketTwo(), search_engine.fetchBucketThree(), search_engine.fetchBucketFour(), search_engine.fetchBucketFive())
.done(function(bucket_one_result, bucket_two_result, bucket_three_result, bucket_four_result, bucket_five_result){
search_engine.bucket_one = bucket_one_result;
console.log('search_engine.bucket_one');console.log(search_engine.bucket_one);
search_engine.bucket_two = bucket_two_result;
console.log('search_engine.bucket_two');console.log(search_engine.bucket_two);
search_engine.bucket_three = bucket_three_result;
console.log('search_engine.bucket_three');console.log(search_engine.bucket_three);
search_engine.bucket_four = bucket_four_result;
console.log('search_engine.bucket_four');console.log(search_engine.bucket_four);
search_engine.bucket_five = bucket_five_result;
console.log('search_engine.bucket_five');console.log(search_engine.bucket_five);
});
这是ajax请求:
fetchBucketOne: function() {
url_params = search_engine.createSearchParams();
return ($.ajax({
type: "GET",
url: "/fetch-bucket-one" + url_params,
contentType : "application/x-www-form-urlencoded",
}));
},
fetchBucketTwo: function() {
url_params = search_engine.createSearchParams();
return ($.ajax({
type: "GET",
url: "/fetch-bucket-two" + url_params,
contentType : "application/x-www-form-urlencoded",
}));
},
fetchBucketThree: function() {
url_params = search_engine.createSearchParams();
return ($.ajax({
type: "GET",
url: "/fetch-bucket-three" + url_params,
contentType : "application/x-www-form-urlencoded",
}));
},
fetchBucketFour: function() {
url_params = search_engine.createSearchParams();
return ($.ajax({
type: "GET",
url: "/fetch-bucket-four" + url_params,
contentType : "application/x-www-form-urlencoded",
}));
},
fetchBucketFive: function() {
url_params = search_engine.createSearchParams();
return ($.ajax({
type: "GET",
url: "/fetch-bucket-five" + url_params,
contentType : "application/x-www-form-urlencoded",
}));
},
以下是通过chrome开发工具加载网络的结果的屏幕截图:
谢谢大家的帮助!
答案 0 :(得分:0)
我会用另一种方式来处理,我的方法是
search_engine.setResult = function(name, result) {
search_engine[name] = result;
}
var fetchList = [
{
name: "bucket_one",
url: "/fetch-bucket-one",
contentType: "application/x-www-form-urlencoded",
successFunction: "setResult",
},
{
name: "bucket_two",
url: "/fetch-bucket-two",
contentType: "application/x-www-form-urlencoded",
successFunction: "setResult",
}
]
for(i in fetchList)
{
var fetchItem = fetchLists[i];
$.ajax({
url: fetchItem.url + searchengine.createSearchParams(),
contentType: fetchItem.contentType,
success: function(data) {
searchengine[fetchItem.successFunction](fetchItem.name, data);
}
})
}