Skip to content

Instantly share code, notes, and snippets.

@jrolfs
Created January 16, 2013 20:31
Show Gist options
  • Select an option

  • Save jrolfs/4550658 to your computer and use it in GitHub Desktop.

Select an option

Save jrolfs/4550658 to your computer and use it in GitHub Desktop.
$.resolve = function(arg) {
var args = arguments,
sliceDeferred = [].slice,
i = 0,
length = args.length,
count = length,
rejected,
deferred = length <= 1 && arg && jQuery.isFunction(arg.promise) ? arg : jQuery.Deferred();
function resolveFunction(i, reject) {
return function( value ) {
rejected = true;
args[ i ] = arguments.length > 1 ? sliceDeferred.call(arguments, 0) : value;
if ( !( --count ) ) {
// Strange bug in FF4:
// Values changed onto the arguments object sometimes end up as undefined values
// outside the $.when method. Cloning the object into a fresh array solves the issue
var fn = rejected ? deferred.rejectWith : deferred.resolveWith;
fn.call(deferred, deferred, sliceDeferred.call(args, 0));
}
};
}
if (length > 1) {
for( ; i < length; i++) {
if (args[ i ] && jQuery.isFunction(args[ i ].promise)) {
args[ i ].promise().then(resolveFunction(i), resolveFunction(i, true));
} else {
--count;
}
}
if (!count) {
deferred.resolveWith(deferred, args);
}
} else if (deferred !== arg) {
deferred.resolveWith( deferred, length ? [ arg ] : [] );
}
return deferred.promise();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment