Skip to content

Instantly share code, notes, and snippets.

@nanxiaobei
Last active August 30, 2021 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanxiaobei/395fb3fba95eaa865ed493b56e9f687b to your computer and use it in GitHub Desktop.
Save nanxiaobei/395fb3fba95eaa865ed493b56e9f687b to your computer and use it in GitHub Desktop.
Scheduler for limit Promises
class Scheduler {
constructor(limit) {
this.count = 0;
this.limit = limit;
this.list = [];
}
add(fn) {
return new Promise((resolve) => {
this.list.push((...args) => fn(...args).then(resolve));
this.run();
});
}
async run() {
if (this.count === this.limit || this.list.length === 0) return;
this.count++;
await this.list.shift()();
this.count--;
this.run();
}
}
export default Scheduler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment