Deferred look up country code via multiple geolocation webapis

now working

by bizamajig

JavaScript

(function($) {
    $.reverseWhen = function(subordinate /* , ..., subordinateN */ ) {
        var i = 0,
            rejectValues = Array.prototype.slice.call(arguments),
            length = rejectValues.length,

            // the count of uncompleted subordinates
            remaining = length !== 1 || (subordinate && jQuery.isFunction(subordinate.promise)) ? length : 0,

            // the master Deferred. If rejectValues consist of only a single Deferred, just use that.
            deferred = remaining === 1 ? subordinate : jQuery.Deferred(),

            // Update function for both reject and progress values
            updateFunc = function(i, contexts, values) {
                return function(value) {
                    contexts[i] = this;
                    values[i] = arguments.length > 1 ? Array.prototype.slice.call(arguments) : value;
                    if (values === progressValues) {
                        deferred.notifyWith(contexts, values);
                    } else if (!(--remaining)) {
                        deferred.rejectWith(contexts, values);
                    }
                };
            },

            progressValues, progressContexts, rejectContexts;

        // add listeners to Deferred subordinates; treat others as rejected
        if (length > 1) {
            progressValues = new Array(length);
            progressContexts = new Array(length);
            rejectContexts = new Array(length);
            for (; i < length; i++) {
                if (rejectValues[i] && jQuery.isFunction(rejectValues[i].promise)) {
                    rejectValues[i].promise().done(deferred.resolve).fail(updateFunc(i, rejectContexts, rejectValues)).progress(updateFunc(i, progressContexts, progressValues));
                } else {
                    --remaining;
                }
            }
        }

        // if we're not waiting on anything, reject the master
        if (!remaining) {
            deferred.rejectWith(rejectContexts,...