限制数量的并发请求
ts
function batchFetch(urls: string[], max: number) {
if (urls.length === 0) {
return Promise.resolve([]);
}
if (max <= 0) {
return Promise.reject(new Error('max must be greater than 0'));
}
const p = new Promise<unknown[]>((resolve) => {
const result: unknown[] = [];
let currentIndex = 0;
let runningCount = 0;
let finishedCount = 0;
function _run() {
const id = currentIndex;
if (runningCount >= max || id >= urls.length) {
return;
}
const url = urls[currentIndex];
currentIndex++;
runningCount++;
fetch(url)
.then((response) => {
result[id] = response;
})
.catch((error) => {
result[id] = error;
})
.finally(() => {
runningCount--;
finishedCount++;
if (finishedCount === urls.length) {
resolve(result);
return;
}
_run();
});
}
for (let i = 0; i < Math.min(max, urls.length); i++) {
_run();
}
});
return p;
}