Created
July 21, 2011 01:10
-
-
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
This file contains 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
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