Skip to main content

Task Queue

Design an API that processes objects sequentially (where each object must wait for the previous one to finish before executing), we can create a task queue. This queue will hold objects (representing tasks) and execute each one only after the previous task has completed.

API Design

class TaskQueue {

queue = Promise.resolve()

enqueue = (task) => {
this.queue = this.queue.then(() => {
console.log('Executing task...');
return task()
}).catch(e => {
console.log(e.message);
})
return queue
}
}


// Example tasks
function task1() {
return new Promise(resolve => {
setTimeout(() => {
console.log("Task 1 completed");
resolve();
}, 1000);
});
}

function task2() {
return new Promise(resolve => {
setTimeout(() => {
console.log("Task 2 completed");
resolve();
}, 500);
});
}

function task3() {
return new Promise(resolve => {
setTimeout(() => {
console.log("Task 3 completed");
resolve();
}, 2000);
});
}

// Create a task queue
const queue = new TaskQueue();

// Enqueue tasks
queue.enqueue(task1);
queue.enqueue(task2);
queue.enqueue(task3);

/*
Executing task...
Task 1 completed
Executing task...
Task 2 completed
Executing task...
Task 3 completed
*/