Created
June 9, 2011 20:43
-
-
Save prozacgod/1017699 to your computer and use it in GitHub Desktop.
node.js synchronize multiple actions
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
/* | |
A simple and elegant function to synchronize multiple functions that expect callback as their last parameter. | |
example: | |
sync(func1, [parms], func2, func3, func4, [parms], callback); | |
Public domain!! | |
please leave me a comment if you like it! | |
*/ | |
function sync() { | |
var args = Array.prototype.slice.call(arguments); | |
var callback = args.slice(-1)[0]; | |
args = args.slice(0,-1); | |
// Prep the results data set | |
var results = []; | |
var l = args.length; | |
for (var i = 0; i < l; i++) { | |
if (typeof args[i] == "function") | |
results.push([args[i], null, null]); | |
else | |
results[results.length-1][1] = args[i]; | |
} | |
var do_nothing = false; | |
// handle all callbacks here | |
function doCallback() { | |
var done = true; | |
var result_parms = []; | |
results.forEach(function(value, key) { | |
result_parms[key] = value[2]; | |
done = done && (value[2] !== null); | |
}); | |
if (done) { | |
do_nothing = true; | |
callback(result_parms); | |
} | |
} | |
results.forEach(function(result, key, original) { | |
function cb() { | |
if (!do_nothing) { | |
result[2] = Array.prototype.slice.call(arguments); | |
doCallback(); | |
} | |
} | |
process.nextTick(function() { | |
args = Array.prototype.slice.call(result[1]); | |
args.push(cb); | |
result[0].apply(null, args); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment