Async Task Queue

HardPromises & Async30 min5 tests

Implement createAsyncQueue() that returns a FIFO queue processing one async task at a time.

Requirements

  • enqueue(asyncFn) — add a task (a function returning a Promise). Returns a promise that resolves with the task's result.
  • size() — return the number of pending (waiting + running) tasks.
  • onEmpty(callback) — register a callback invoked when the queue becomes empty.
  • Tasks are processed one at a time in FIFO order. The next task starts only after the previous completes.

Example

const q = createAsyncQueue();
q.enqueue(() => delay(50).then(() => 'a'));
q.enqueue(() => delay(30).then(() => 'b'));
q.onEmpty(() => console.log('done!'));
Hints (5)
  1. Use an internal array as the queue, storing each task along with its resolve/reject.
  2. enqueue should return a new Promise whose resolve/reject are stored with the task.
  3. Use a boolean flag to track if the queue is currently processing.
  4. The process function should loop through the queue, awaiting each task in order.
  5. After the queue empties, call all registered onEmpty callbacks.

Topics

  • Promises & Async

Asked at

Amazon · Microsoft · Uber · Stripe

Join Us
blur