Q24: Build a Priority-Based Asynchronous Job Queue

Implement an asynchronous job queue that sorts queued tasks by numeric priority values so higher priority jobs execute first under concurrency limits.

Priority Async Queue
class PriorityAsyncQueue {
  constructor(concurrency = 2) {
    this.concurrency = concurrency;
    this.running = 0;
    this.heap = [];
  }

  enqueue(task, priority = 0) {
    return new Promise((resolve, reject) => {
      this.heap.push({ task, priority, resolve, reject });
      this.heap.sort((a, b) => b.priority - a.priority);
      this.processNext();
    });
  }

  processNext() {
    if (this.running >= this.concurrency || this.heap.length === 0) return;
    
    const { task, resolve, reject } = this.heap.shift();
    this.running++;
    
    Promise.resolve(task())
      .then(resolve)
      .catch(reject)
      .finally(() => {
        this.running--;
        this.processNext();
      });
  }
}
💡 Tasks are sorted by priority score upon insertion, ensuring highest-priority items shift out first when worker slots open.
Key Takeaways
  • Orders pending tasks by priority before processing.
  • Enforces concurrency limits while processing high-priority tasks first.
Knowledge Check

In what order are pending tasks processed by the PriorityAsyncQueue above?