@cc-heart/utils
Version:
🔧 javascript common tools collection
25 lines (22 loc) • 729 B
JavaScript
import { isUndef } from '../lib/validate.js';
async function useConcurrency(tasks, maxConcurrency) {
if (isUndef(maxConcurrency)) {
console.warn('maxConcurrency is undefined');
return null;
}
const ret = [];
const excluding = [];
for (let i = 0; i < tasks.length; i++) {
const res = tasks[i]();
ret.push(res);
if (maxConcurrency < tasks.length) {
const p = res.then(() => excluding.splice(excluding.indexOf(p), 1));
excluding.push(p);
if (excluding.length >= maxConcurrency) {
await Promise.race(excluding);
}
}
}
return Promise.all(ret);
}
export { useConcurrency };