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)
- Use an internal array as the queue, storing each task along with its resolve/reject.
- enqueue should return a new Promise whose resolve/reject are stored with the task.
- Use a boolean flag to track if the queue is currently processing.
- The process function should loop through the queue, awaiting each task in order.
- After the queue empties, call all registered onEmpty callbacks.
Topics
- Promises & Async
Asked at
Amazon · Microsoft · Uber · Stripe
