Skip to content

Instantly share code, notes, and snippets.

@asarode
Last active October 11, 2015 02:32
Show Gist options
  • Save asarode/69b5b3e33f806b6a0323 to your computer and use it in GitHub Desktop.
Save asarode/69b5b3e33f806b6a0323 to your computer and use it in GitHub Desktop.
'use strict'
function parallel(tasks, max, done) {
let running = 0
let completed = 0
next()
function taskCompleted() {
completed++
console.log(`finished task #${completed}`)
if (completed === tasks.length) return done()
running--
next()
}
function next() {
while (running < max && completed + max - 1 < tasks.length) spawnNext()
}
function spawnNext() {
tasks[completed](taskCompleted)
running++
console.log(`added task, now running: ${running}`)
}
}
function asyncThing(callback) {
setTimeout(() => {
callback()
}, Math.random() * 2500)
}
parallel([asyncThing, asyncThing, asyncThing, asyncThing], 3, () => {
console.log('finished everything!')
})
'use strict'
function queue(tasks, callback) {
function process(index) {
if (index === tasks.length) {
console.log('queue has finished processing all tasks')
if (callback) return callback()
return
}
tasks[index](index, err => {
if (err) console.log('error occured', err)
process(index + 1)
})
}
process(0)
}
function asyncThing(index, callback) {
setTimeout(() => {
console.log(`did async thing #${index}`)
callback(null)
}, 500)
}
const tasks = [asyncThing, asyncThing, asyncThing, asyncThing, asyncThing]
queue(tasks)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment