Skip to content

Instantly share code, notes, and snippets.

@sounishnath003
Last active August 25, 2022 17:49
Show Gist options
  • Save sounishnath003/7173a924ec0197f73b904eb41f9ee60d to your computer and use it in GitHub Desktop.
Save sounishnath003/7173a924ec0197f73b904eb41f9ee60d to your computer and use it in GitHub Desktop.
Easily perform Concurrent Execution to LongRunning Processes using Simple ConcurrentQueue. Feel free to improve and share feedback.
const delay = (seconds = 1) =>
new Promise((resolve, reject) =>
setTimeout(() => {
resolve("process completed...");
}, seconds * 1000)
);
const tasks = [
delay(1),
delay(4),
delay(8),
delay(4),
delay(7),
delay(4),
delay(10),
delay(5),
delay(0),
delay(8),
delay(1),
delay(10),
delay(7),
];
class ConcurrencyPromiseQueueExecutor {
constructor(promises = [], concurrentExeCount = 1) {
this.concurrent = concurrentExeCount;
this.total = promises.length;
this.todo = promises;
this.running = [];
this.completed = [];
}
get runAnother() {
return this.todo.length && this.running.length < this.concurrent;
}
graphTasks() {
var { todo, running, completed } = this;
const state = {
todo,
running,
completed,
};
console.log(JSON.stringify(state));
}
run() {
while (this.runAnother) {
var promise = this.todo.shift();
this.running.push(promise);
promise.then(() => {
this.completed.push(this.running.shift());
this.graphTasks();
this.run();
});
this.graphTasks();
}
}
}
const promiseQueue = new ConcurrencyPromiseQueueExecutor(tasks, 3);
promiseQueue.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment