Skip to content

Instantly share code, notes, and snippets.

@prozacgod
Created June 9, 2011 20:43
Show Gist options
  • Select an option

  • Save prozacgod/1017699 to your computer and use it in GitHub Desktop.

Select an option

Save prozacgod/1017699 to your computer and use it in GitHub Desktop.

Revisions

  1. prozacgod revised this gist Jun 9, 2011. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion synchro.js
    Original 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], func1, func1, func1, [parms], callback);
    sync(func1, [parms], func2, func3, func4, [parms], callback);
    Public domain!!
  2. @invalid-email-address Anonymous created this gist Jun 9, 2011.
    54 changes: 54 additions & 0 deletions synchro.js
    Original 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);
    });
    });
    }