Skip to content

Instantly share code, notes, and snippets.

@xinyii
Created April 15, 2021 12:27
Show Gist options
  • Save xinyii/b5c3a01335ce3fe4f5218320722f9f64 to your computer and use it in GitHub Desktop.
Save xinyii/b5c3a01335ce3fe4f5218320722f9f64 to your computer and use it in GitHub Desktop.
[Blocking Task Queue] #nodejs
const EventEmitter = require('events')
class TaskQueue extends EventEmitter {
constructor(size) {
super()
this.size = size
this.jobs = new Set()
}
async push(task) {
while (this.jobs.size >= this.size) {
await new Promise(resolve => this.once('pop', resolve))
}
const id = Symbol()
this.jobs.add(id)
task().finally(() => {
this.jobs.delete(id)
this.emit('pop')
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment