Skip to content

Instantly share code, notes, and snippets.

@jupemara
Created June 23, 2019 08:00
Show Gist options
  • Save jupemara/202dfb833bb33184695f3042eac0a434 to your computer and use it in GitHub Desktop.
Save jupemara/202dfb833bb33184695f3042eac0a434 to your computer and use it in GitHub Desktop.
pure nodejs Promise queue
class TaskQueue {
constructor (con) {
this.con = con;
this.running = 0;
this.queue = [];
}
pushTask (task) {
this.queue.push(task);
this.next();
}
next() {
while (this.running < this.con && this.queue.length) {
const task = this.queue.shift();
console.log('started task');
task().then(() => {
this.running--;
this.next();
});
this.running++;
}
}
}
(() => {
const t1 = () => {
return new Promise(resolve => {
setTimeout(() => {
console.log(1);
resolve();
}, Math.random() * (1000 - 50) + 50);
});
};
const t2 = () => {
return new Promise(resolve => {
setTimeout(() => {
console.log(2);
resolve();
}, Math.random() * (3000 - 500) + 500);
});
};
const q = new TaskQueue(2);
q.pushTask(t1);
q.pushTask(t1);
q.pushTask(t2);
q.pushTask(t2);
q.pushTask(t1);
q.pushTask(t2);
console.log('started');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment