Last active
October 11, 2015 02:32
-
-
Save asarode/69b5b3e33f806b6a0323 to your computer and use it in GitHub Desktop.
Revisions
-
asarode created this gist
Oct 11, 2015 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,35 @@ '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 hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,27 @@ '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)