Created
April 15, 2021 12:27
-
-
Save xinyii/b5c3a01335ce3fe4f5218320722f9f64 to your computer and use it in GitHub Desktop.
[Blocking Task Queue] #nodejs
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
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