Skip to content

Instantly share code, notes, and snippets.

@dstrelau
Created July 17, 2010 04:49
Show Gist options
  • Save dstrelau/479251 to your computer and use it in GitHub Desktop.
Save dstrelau/479251 to your computer and use it in GitHub Desktop.
[parallel] time coffee usage.coffee
{ '0': 'response for /movies'
, '1': 'response for /books'
}
{ '0': 'response for /tv-shows'
, '1': 'response for /blogs'
}
real 0m1.234s
user 0m0.178s
sys 0m0.050s
exports.ize: (actions...,callback) ->
results: []
counter: actions.length
cb: (result) ->
results.push(result)
callback.apply(null, results) if results.length == actions.length
action(cb) for action in actions
sys: require 'sys'
parallel: require './parallel'
# an async function that takes a callback as its last argument
fetch: (url, callback) ->
setTimeout (-> callback "response for $url"), 1000
# To parallelize, either curry the async function:
Function::curry: ->
self: this
args: Array.prototype.slice.call(arguments)
->
self.apply(this, args.concat(Array.prototype.slice.call(arguments)));
parallel.ize(
fetch.curry('/movies'),
fetch.curry('/books'),
(movies,books) -> sys.puts sys.inspect arguments
)
# Or define a curried wrapper
parallel_fetch: (url) ->
(callback) -> fetch(url, callback)
parallel.ize(
parallel_fetch('/tv-shows'),
parallel_fetch('/blogs'),
(tv,blogs) -> sys.puts sys.inspect arguments
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment