function chain(functions, args) {
        var deferred = $.Deferred();

        function chainHelper(index, args) {
            if (functions.length === index) {
                deferred.resolveWith(null, args);
            } else {
                var nextFunction = functions[index++];
                try {
                    var responseOrPromise = nextFunction.apply(null, args);
                    if (responseOrPromise.hasOwnProperty("done") &&
                            responseOrPromise.hasOwnProperty("fail")) {
                        responseOrPromise.done(function () {
                            chainHelper(index, arguments);
                        });
                        responseOrPromise.fail(function () {
                            deferred.rejectWith(null, arguments);
                        });
                    } else {
                        chainHelper(index, [responseOrPromise]);
                    }
                } catch (e) {
                    deferred.reject(e);
                }
            }
        }

        chainHelper(0, args || []);

        return deferred.promise();
    }
Chains a series of synchronous and asynchronous (jQuery promise-returning) functions
together, using the result of each successive function as the argument(s) to the next.
A promise is returned that resolves with the result of the final call if all calls
resolve or return normally. Otherwise, if any of the functions reject or throw, the
computation is halted immediately and the promise is rejected with this halting error.

@param {Array.<function(*)>} functions Functions to be chained
@param {?Array} args Arguments to call the first function with
@return {jQuery.Promise} A promise that resolves with the result of the final call, or
     rejects with the first error.