【发布时间】:2021-01-29 01:55:17
【问题描述】:
我正在尝试从 Web 服务中保存一些信息,这是很多数据,我必须发出很多 Ajax 请求,在这么快的许多请求之后,服务器只是抛出“请求太多”,这使得感觉...
我的代码如下所示:
function getDataFromWS()
{
define some vars
$ make an ajax request to MY database to get every item i will request on the external WS
(that query returns like 150 items to arrayFromResponse)
//Loop into the array with 150 items
arrayFromResponse.forEach((element)=>{
//For loop to make request for each day of the month e.g. August 31 days
for(let i = 1; i <= 31; i++){
//change uri to match each day using i
uriData.date = '2020-08-0'+i;
//This is where after many requests it throws error 429 "Too many"
$.ajax({
data: uriData,
url: uri,
type: 'GET',
async: false,
success : function(response){
//Save data from response to some arrays I use
},
error: function(response){
console.log(response);
console.log('Error');
}
});
}
})
//After all that looping and requests make a CSV file
buildCSVfile(dataFromResponses);
}
我需要所有这些代码都是同步的,我假设我需要使用 setTimeout 之类的东西,因为我试过了,但是 buildCSVfile() 函数在循环之前执行,我猜延迟应该在每个 ajax 请求之后在 for 循环的日期中。每个请求可能需要 10 秒,所以它不会说太多请求?所有核心代码都在success函数中。我不需要这个很快,只是为了确保获得所有信息,每个项目和每个月的每一天。
感谢您提供的任何帮助。
【问题讨论】:
-
“我需要所有这些代码都是同步的” 为什么? BTW,如果你添加
setTimeout,那么它将不再是同步的。 -
@HereticMonkey 由于保存数据的 CSV 文件,我只需要延迟每个 ajax 请求,并且在 4500 个请求结束时,将文件与所有内容一起保存。它现在可以工作,但只能处理 50 个请求。
-
考虑另一种不需要同步的技术。查看Sending one AJAX request at a time from a loop的答案
标签: javascript jquery ajax xmlhttprequest