Skip to content

Instantly share code, notes, and snippets.

@ded
Created July 21, 2011 01:10
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ded/1096301 to your computer and use it in GitHub Desktop.
Save ded/1096301 to your computer and use it in GitHub Desktop.
call multiple async methods in parallel and receive the result in a callback
function parallel() {
var args = Array.apply(null, arguments)
, callback = args.pop()
, returns = []
, len = 0
args.forEach(function (el, i) {
el(function () {
var a = Array.apply(null, arguments)
, e = a.shift()
if (e) return callback(e)
returns[i] = a
if (args.length == ++len) returns.unshift(null) && callback.apply(null, returns)
})
})
}
parallel(
function (fn) {
getTimeline(function (e, timeline) {
fn(e, timeline)
})
}
, function (fn) {
getUser(function (e, user) {
fn(e, user)
})
}
, function (e, timeline, user) {
if (e) return console.log(e)
console.log(timeline, user)
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment