Last active
August 30, 2021 10:12
-
-
Save nanxiaobei/395fb3fba95eaa865ed493b56e9f687b to your computer and use it in GitHub Desktop.
Scheduler for limit Promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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