Created
May 17, 2012 20:41
-
-
Save BFalkner/2721476 to your computer and use it in GitHub Desktop.
$.whenAll
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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