Open Vitaminaq opened 2 years ago
class AsyncWorker { queue = []; count = 0; constructor(capacity) { this.capacity = capacity; } shiftQueue() { console.log('当前执行数:', this.count); this.count--; console.log('当前队列长度:', this.queue.length); const t = this.queue.shift(); t && this.exec(t); } async exec(task) { if (this.count < this.capacity) { this.count++; try { const r = await task(); this.shiftQueue(); return r; } catch (e) { this.shiftQueue(); return e; } } else { this.queue.push(task) } } } function cp(time, s) { return () => new Promise((resolve, reject) => { setTimeout(() => { s ? resolve() : reject(); }, time) }) } const a = new AsyncWorker(2); for (let i = 1; i < 10; i++) { a.exec(cp(i * 1000, i % 2)) }