Skip to content

Instantly share code, notes, and snippets.

@BFalkner
Created May 17, 2012 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BFalkner/2721476 to your computer and use it in GitHub Desktop.
Save BFalkner/2721476 to your computer and use it in GitHub Desktop.
$.whenAll
var // Static reference to slice
sliceDeferred = [].slice;
/* $.when that waits for everything to return before failing */
function whenAll( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred(),
promise = deferred.promise(),
fail = false;
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
fail? deferred.reject() :
deferred.resolveWith( deferred, args );
}
};
}
function rejectFunc( i ) {
var func = resolveFunc(i);
return function (value) {
fail = true;
return func(value);
}
}
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
if ( length > 1 ) {
for ( ; i < length; i++ ) {
if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), rejectFunc(i), progressFunc(i) );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment