如何降低请求速度?



我有过快请求的问题。当我的脚本每秒发出太多请求时,Google抛出一个错误net::ERR_INSUFFICIENT_RESOURCES

我想每20ms发出一个请求。我怎样才能做到呢?


这是我的主函数现在的样子…

const symbolsArr = reader.result.split("n").map((str) => str.trim()); //symbolsArr is just rergular array, except it's source is from .txt file
function loopFunction(error_symbol) {
for (const symbol of symbolsArr) {
setTimeout(getData(symbol), 5000); //I tried to use setTimeout but it not helps
}
return console.log(error_symbol);
}
loopFunction(error_symbols);

And my fetcher…

error_symbols = [];
function getData(symbol) {
fetch(
`https://cors-anywhere.herokuapp.com/` +
`https://eodhistoricaldata.com/api/fundamentals/${symbol}?api_token= (don't look at my secret token :))`,
{
method: "get",
}
)
.then((res) => {
if (res.ok) {
return res.json();
} else {
throw new Error(`Symbol ${symbol} is 'empty'`);
}
})
.then((data) => {
console.log(data);
var myJSON = JSON.stringify(data);
saveFile(myJSON, `${symbol}-json.txt`, "text/plain");
})
.catch((error) => {
error_symbols.push(symbol);
throw error + symbol;
});
}

很简单,我必须把冷却时间设置在fetcher

try this

const symbolsArr = reader.result.split("n").map((str) => str.trim()); //symbolsArr is just rergular array, except it's source is from .txt file
async function loopFunction(error_symbol) {
for (const symbol of symbolsArr) {
await setTimeout(getData(symbol), 5000); //I tried to use setTimeout but it not helps
}
return console.log(error_symbol);
}
loopFunction(error_symbols);

取回API正在使用异步承诺来处理请求。

我很确定你需要设置一个await,让循环在每个循环上等待,直到完成。

最新更新