全栈应用开发中并发式请求
class SlotLimiter {
constructor(maxConcurrency) {
this.max = maxConcurrency; // 槽位总数,即允许同时执行的任务数量上限
this.running = 0; // 当前正在执行的任务数(已占用的槽位数)
this.queue = []; // 等待队列,存放暂时无法执行的任务的启动函数
}add(task) {
return new Promise((resolve, reject) => {
const runTask = () => {
this.running++;
Promise.resolve(task())
.then(resolve, reject)
.finally(() => {
this.running--;
this.next();
});
};
if (this.running < this.max) {
runTask();
} else {
this.queue.push(runTask);
}
});
}
next() {
if (this.queue.length && this.running < this.max) {
const nextTask = this.queue.shift();
nextTask();
}
}
class DistributedLimiter {
constructor(options) {
this.pools = new Map();
for (const [key, max] of Object.entries(options)) {
this.pools.set(key, new SlotLimiter(max));
}
}
评论
发表评论