Created
September 8, 2018 23:05
-
-
Save Lazhari/fdeedb0dfeb69e0def3a33aef3cbc665 to your computer and use it in GitHub Desktop.
Logging concurrent tasks with Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const logUpdate = require("log-update"); | |
const toX = () => "X"; | |
const delay = seconds => | |
new Promise(resolves => { | |
setTimeout(resolves, seconds * 1000); | |
}); | |
const tasks = [ | |
delay(4), | |
delay(6), | |
delay(4), | |
delay(3), | |
delay(5), | |
delay(7), | |
delay(9), | |
delay(10), | |
delay(3), | |
delay(5) | |
]; | |
class PromiseQueue { | |
constructor(promises = [], concurrentCount = 1) { | |
this.concurrentCount = concurrentCount; | |
this.total = promises.length; | |
this.todo = promises; | |
this.running = []; | |
this.complete = []; | |
} | |
get runAnother() { | |
return this.running.length < this.concurrentCount && this.todo.length; | |
} | |
graphTasks() { | |
const { todo, running, complete } = this; | |
logUpdate(` | |
todo: [${todo.map(toX)}] | |
running: [${running.map(toX)}] | |
complete: [${complete.map(toX)}] | |
`); | |
} | |
run() { | |
while (this.runAnother) { | |
const promise = this.todo.shift(); | |
promise.then(() => { | |
this.complete.push(this.running.shift()); | |
this.graphTasks(); | |
this.run(); | |
}); | |
this.running.push(promise); | |
this.graphTasks(); | |
} | |
} | |
} | |
const 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