1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Task { constructor(count) { this.maxCount = count; this.runCount = 0; this.tasks = []; }
add(task) { return new Promise((resolve, reject) => { this.tasks.push({ task, resolve, reject, }); this.run(); }); }
run() { while (this.tasks.length && this.runCount < this.maxCount) { const { task, resolve, reject } = this.tasks.shift(); this.runCount++; task() .then(resolve, reject) .finally(() => { this.runCount--; this.run(); }); } } }
|