Created
May 3, 2019 13:44
-
-
Save EminQasimov/7ad0c9a95216240cabb7f215f10d2912 to your computer and use it in GitHub Desktop.
concurrency with promises
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 delay = second => () => new Promise((resolve, rejects) => { | |
setTimeout(() => { | |
resolve() | |
}, second * 1000); | |
}) | |
// some tasks that take long time | |
let tasks = [ | |
delay(0), | |
delay(3), | |
delay(3), | |
delay(3), | |
delay(1), | |
delay(1), | |
delay(1), | |
delay(3), | |
delay(3), | |
delay(3), | |
delay(3), | |
delay(3) | |
] | |
class PromiseQueue{ | |
constructor(tasks = [], concurrent = 1){ | |
this.tasks = tasks | |
this.running = [] | |
this.complete = [] | |
this.concurrent = concurrent | |
} | |
isRunning(){ | |
return (this.running.length < this.concurrent ) && (this.tasks.length !== 0 ) | |
} | |
run(){ | |
return new Promise((resolve,reject)=>{ | |
let start = () => { | |
this.graph()//logging proccess | |
while(this.isRunning()){ | |
const job = this.tasks.shift() | |
job().then(() => { | |
//job is done? remove it from running queue, add to complete queue then start next job that remains | |
this.complete.push(this.running.shift()) | |
start() | |
}) | |
this.running.push(job) | |
this.graph() | |
} | |
if(this.running.length == 0){ | |
resolve("done") | |
} | |
} | |
start() | |
})//promise | |
} | |
graph(){ | |
console.clear() | |
console.log(` | |
tasks: ${this.tasks.map(x => "❌")} | |
running: ${this.running.map(x => "🔄")} | |
completed: ${this.complete.map(x => "✔")} | |
`) | |
} | |
}// class | |
const queue = new PromiseQueue(tasks, 3)// how many jobs need to run together | |
queue.run().then((arr) => { | |
console.log(arr) | |
console.log("\x07");// beeep sound | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment