Serial task queue
Implement createQueue(). queue.add(task) takes a function that returns a promise. Tasks run one at a time, in the order they were added. add returns a promise that settles as that task does. A task that fails does not stop the queue. In the tests a task is [addedAt, duration, value, fails]; the answer shows each task's outcome [status, value, time], when each task started, and the peak number running at once.
Start from
function createQueue() {
// Return { add(task) } that runs tasks one at a time.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Keep one promise: the tail of the chain. A new task runs in a then on that tail.
Hint 2
Return the task's own promise to the caller, but store a version of it that never rejects as the new tail. Otherwise one failure breaks every later task.
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function createQueue() {
let tail = Promise.resolve();
return {
add(task) {
const run = tail.then(() => task());
tail = run.catch(() => {});
return run;
},
};
}What an interviewer looks for
Saving edits in order, or sending messages one by one, needs a queue. The short solution with a promise chain shows real understanding of then.