Last active
December 19, 2015 03:49
-
-
Save pyykkis/5892882 to your computer and use it in GitHub Desktop.
Run n async operations concurrently
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 characters
Q = require 'q' | |
_ = require 'underscore' | |
photos = [1..100] | |
partition = (n, coll) -> | |
_.values(_.groupBy(coll, (x, i) -> Math.floor i/n)) | |
scaleImage = (img, i) -> | |
Q.delay(200).then -> console.log "processed image #{i}" | |
processGroup = (task) -> (g) -> -> | |
Q.allSettled g.map task | |
runTasks = (concurrency, task, coll) -> | |
partition(concurrency, coll) | |
.map(processGroup task) | |
.reduce(Q.when, Q()) | |
runTasks 8, scaleImage, photos |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment