PromiseQueue
支持限制并发数
class PromiseQueue {
limit: number
active: number
queue: Array<() => Promise<any>>
constructor(limit = 3) {
// 并发限制
this.limit = limit;
// 当前活跃数
this.active = 0;
// 异步队列
this.queue = [];
}
push(p: () => Promise<any>) {
this.queue.push(p);
this.next();
return this;
}
next() {
if (this.active >= this.limit || !this.queue.length) {
return;
}
this.active++;
const promiseFac = this.queue.shift();
if(promiseFac) {
let promise = promiseFac();
promise.then((res) => {
console.log(res)
this.active--;
this.next();
},(error) => {
console.log(error)
this.active--;
this.next();
})
}
}
}