Last active
June 13, 2021 14:48
-
-
Save dominathan/7b0e0b11ed53804f97ef5173326953af to your computer and use it in GitHub Desktop.
taskqueue.js
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 { | |
constructor(concurrent) { | |
this.concurrent = concurrent || 1 | |
this.unprocessed = [] | |
this.processing = [] | |
this.processingCount = 0 | |
this.eventEmitter = new EventEmitter() | |
this.eventEmitter.on('processed', () => { | |
this.processing.push(this.unprocessed.shift()) | |
this.next() | |
}) | |
} | |
runTask(task) { | |
this.unprocessed.push(task) | |
if(this.processingCount < this.concurrent) { | |
this.processing.push(this.unprocessed.shift()) | |
this.next() | |
} | |
} | |
async next() { | |
const func = this.processing.shift() | |
if(func) { | |
this.processingCount += 1 | |
await func() | |
this.processingCount -= 1 | |
if(this.processingCount < this.concurrent) { | |
this.eventEmitter.emit('processed') | |
} | |
} | |
} | |
} | |
function task() { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
resolve("stuff") | |
}, 1000) | |
}).then(console.log) | |
} | |
const queue = new TaskQueue(4) | |
queue.runTask(task) | |
queue.runTask(task) | |
queue.runTask(task) | |
queue.runTask(task) | |
queue.runTask(task) | |
queue.runTask(task) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment