Skip to content

Instantly share code, notes, and snippets.

@pyykkis
Last active December 19, 2015 03:49
Show Gist options
  • Save pyykkis/5892882 to your computer and use it in GitHub Desktop.
Save pyykkis/5892882 to your computer and use it in GitHub Desktop.
Run n async operations concurrently
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