以下是一个使用JavaScript解决并发数的示例代码:
class ConcurrentLimit {
constructor(limit) {
this.limit = limit;
this.running = 0;
this.queue = [];
}
run(fn) {
if (this.running < this.limit) {
this.running++;
fn().then(() => {
this.running--;
this.next();
});
} else {
this.queue.push(fn);
}
}
next() {
if (this.running < this.limit && this.queue.length > 0) {
this.running++;
const fn = this.queue.shift();
fn().then(() => {
this.running--;
this.next();
});
}
}
}