Question #
Design and implement an AsyncTaskQueue class that manages the execution of asynchronous tasks with a specified maximum concurrency limit. The queue should execute tasks in the order they are added (FIFO) and ensure that no more than the specified number of tasks run concurrently. If a task’s Promise rejects, the rejection should be silently ignored, allowing the queue to continue processing remaining tasks.
Solution #
class AsyncTaskQueue {
constructor(concurrency) {
this.concurrency = concurrency
this.taskQueue = []
this.runningCount = 0
}
async runTask(task) {
try {
await task()
}
catch (err) {
// just continut
}
finally {
this.runningCount--
this.runNextTask()
}
}
runNextTask() {
if (this.runningCount < this.concurrency && this.taskQueue.length > 0) {
const nextTask = this.taskQueue.shift()
this.runningCount++
this.runTask(nextTask)
}
}
addTask(task) {
this.taskQueue.push(task)
this.runNextTask()
}
}