mcgraths
2/29/2012 - 7:16 AM

synchelper

synchelper

var _ = require("underscore");

/**
  * First argument is the callback to call when all are done
  * all other callbacks are functions of the form
  *   function (callback, ...) { }
  * and must call callback when they are done
  * the ... will be any additional parameters from the previous step as
  * the first parameter of all functions is partially applied to be the callback
  * on creation of sequence.
  */
var waitForAll = function (/*...*/) {
    var doneCallback = _.first(arguments),
        actions,
        callback = function () {
            if (actions.length) {
                actions.shift().apply(null,arguments);
            } else {
                doneCallback();
            }
        };
    actions = _.chain(arguments).tail().map(function (f) {
        return _.bind(f, null, callback);
    }).value();

    callback();
};

exports.waitForAll = waitForAll;