gpt4 book ai didi

jquery - 一次执行总共 n 个调用中的 5 个 ajax 调用

转载 作者:行者123 更新时间:2023-12-01 01:31:36 24 4
gpt4 key购买 nike

我目前有一个从初始 ajax 调用中获得的 id 数组,我需要在其中进行后续调用。假设该数组中有 20 个 id。

我现在需要做的是一次只进行 5 个调用,因为我们不想让服务器重载。一旦这 5 个完成,就开始下一个 5。一旦全部完成,我需要 console.log('done');

var ids = [3,5,2,6,7,13,35,27,8,5,3,5,26,57,18,3,42,67];
var results = {};

var ajaxCall = function(id) {
$.ajax({
url: '/url?id=' + id, method: 'GET'})
.complete(function(data) {
results[id] = data;
});
}

最佳答案

您需要使用 setInterval 来检查每个 5 AJAX 调用以及最后一组 5 条记录,clearInterval 如下代码所示。

检查下面的示例,如何在处理每个 Ajax 调用后获取一组 5 Ajax 调用console.log('completed');

function make5call()

上述函数将简单地从数组请求下5个 id

function initTimer()

上面的计时器将检查所有5个Ajax请求是否已完成,然后启动下一个一组5个请求,如果全部完成,则clearInterval

var ids = [3, 5, 2, 6, 7, 13, 35, 27, 8, 5, 3, 5, 26, 57, 18, 3, 42, 67];
//var ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19];

var results = {};
var length = ids.length;
var j = 0;
var pendingAJAX = 5; // Set of ajax call in one go
var complete = false;
var totalCompleted = 0;

// Ajax request function
var ajaxCall = function(id) {
$.ajax({
url: '/url?id' + id,
method: 'GET'
})
.complete(function(data) {
results[id] = data;
console.log(id);
pendingAJAX--; //After each complete decrement one
totalCompleted++; //Track for completed Ajax
// If all sets are completed and total is also same as your ids
if (complete && totalCompleted == ids.length) {
console.log('completed');
}
});
}

var make5call = function() {

for (var i = 0; i < 5; i++) {
// If all Ajax finished set complete to true
if (j == ids.length) {
complete = true;
}
if (j < ids.length) {
ajaxCall(ids[j]); //request Ajax
j++;
}
}
}

// Timer to check when to call for next 5 request
var initTimer = function() {

var timer = null;
timer = window.setInterval(function() {

// Either all are completed or 5 Ajax complted clear interval
if (pendingAJAX == 0 || complete) {
timer = window.clearInterval(timer);
timer = null;
// If All are not finished yet start timer again
if (!complete) {
pendingAJAX = 5;
initTimer();
make5call();
}
}
}, 100);

}

initTimer();
make5call();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

关于jquery - 一次执行总共 n 个调用中的 5 个 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45973958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com