Last active
October 11, 2015 02:32
-
-
Save asarode/69b5b3e33f806b6a0323 to your computer and use it in GitHub Desktop.
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
'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!') | |
}) |
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
'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