Created
January 23, 2019 12:25
-
-
Save sjy/8f59e4190aa1dc0c4a92a7920f2c0c02 to your computer and use it in GitHub Desktop.
quene with max parallel task limits
This file contains hidden or 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
export default class RequestQuene { | |
constructor(limits = 10, duration = 200) { | |
this.duration = duration | |
this.limits = limits | |
this.q = [] | |
this.intervalId = null | |
this.intervalDuration = duration | |
this.numOfRunning = 0 | |
} | |
check = () => { | |
if (this.numOfRunning < this.limits) { | |
this.q.splice(0, this.limits - this.numOfRunning).forEach(run => run()) | |
if (this.q.length === 0 && this.intervalId) { | |
clearInterval(this.intervalId) | |
this.intervalId = null | |
} | |
} | |
} | |
enquene(run) { | |
this.q.push(run) | |
if (!this.intervalId) { | |
this.intervalId = setInterval(this.check, this.intervalDuration) | |
} | |
} | |
add(request) { | |
return new Promise((resolve, reject) => { | |
const run = () => { | |
this.numOfRunning++ | |
try { | |
request() | |
.then(res => { | |
resolve(res) | |
}, err => { | |
reject(err) | |
}) | |
.finally(() => { | |
this.numOfRunning-- | |
}) | |
} catch (e) { | |
this.numOfRunning-- | |
reject(e) | |
} | |
} | |
if (this.numOfRunning < this.limits) { | |
run() | |
} else { | |
this.enquene(run) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment