Skip to content

Instantly share code, notes, and snippets.

@matthewblewitt
Created November 22, 2018 08:39
Show Gist options
  • Save matthewblewitt/12a77668c693cb769d16c89166296c50 to your computer and use it in GitHub Desktop.
Save matthewblewitt/12a77668c693cb769d16c89166296c50 to your computer and use it in GitHub Desktop.
Promise Queue
var delay = (seconds) => new Promise((resolves) => {
setTimeout(function(){
console.log(seconds);
resolves();
}, seconds*1000);
});
var tasks = [
delay(2),
delay(4),
delay(6),
delay(8),
delay(10)
];
class PromiseQueue {
constructor(promises=[], concurrentCount=1) {
this.concurrent = concurrentCount;
this.total = promises.length;
this.todo = promises;
this.running = [];
this.complete = [];
}
get runAnother() {
return (this.running.length < this.concurrent) && this.todo.length;
}
graphTasks() {
var { todo, running, complete } = this;
console.log(`
todo: [${todo.map( () => 'X')}]
running: [${running.map( () => 'X')}]
complete: [${complete.map( () => 'X')}]
`);
}
run() {
while (this.runAnother) {
var promise = this.todo.shift();
promise.then(() => {
this.complete.push(this.running.shift());
this.graphTasks();
this.run();
})
this.running.push(promise);
this.graphTasks();
}
}
}
delayQueue = new PromiseQueue(tasks, 2);
delayQueue.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment