带限制的并行获取



当前使用

async function getAllUrls(urls) {
try {
var data = await Promise.all(
urls.map(
url =>
fetch(url).then(
(response)
)));
return (data)
} catch (error) {
console.log(error)
throw (error)
}}

但是url通常是20多个链接的数组,这并不能让api速率限制器非常满意,我正在寻找的是限制它一次可以发送多少请求的方法,例如,一次只能发送5个请求,在它完成后再发送其他5个

一种简单的方法是分批提取它们,在请求下一批之前等待速率限制期:

const sleep = (ms) =>
new Promise((resolve) => {
setTimeout(resolve, ms);
});
/**
* @param {string[]} urls
* @param {number} delayInterval
* @param {number} batchSize
*/
const fetchInBatches = async (urls, delayInterval, batchSize) => {
const remaining = [...urls];
const responses = [];
while (remaining.length !== 0) {
const batch = remaining.splice(0, batchSize);
const [batchResponses] = await Promise.all([
Promise.all(batch.map((url) => fetchUrl(url))),
sleep(delayInterval),
]);
responses.push(...batchResponses);
}
return responses;
};

一个更好且技术上更具挑战性的方法是编写一个速率受限的请求函数,该函数可用于向速率受限的API发出任何任意请求。

嘿,你可以使用js的slice((函数。。例如

urls.slice(0,5).map(.......

在slice((函数中,0是数据数组的起点,而5是终点。你可以将5设置为任何你喜欢的值。如果你有任何问题,请告诉我。我会尽力帮助你的。。

最新更新