Created
June 9, 2011 20:43
-
-
Save prozacgod/1017699 to your computer and use it in GitHub Desktop.
Revisions
-
prozacgod revised this gist
Jun 9, 2011 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -2,7 +2,7 @@ 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!! -
There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,54 @@ /* A simple and elegant function to synchronize multiple functions that expect callback as their last parameter. example: sync(func1, [parms], func1, func1, func1, [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); }); }); }