Last active
December 23, 2015 21:59
-
-
Save pangorgo/6699985 to your computer and use it in GitHub Desktop.
jQuery.whenAll() is an alternative to jQuery.when() function. Only difference is that whenAll() function do not trigger reject on master deffered immediately after failing any of internal deferreds, but waits for all internal deferreds to change state and then trigger master deffered reject.
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
jQuery.whenAll = function( subordinate /* , ..., subordinateN */ ) { | |
//console.log(arguments); | |
var i = 0, | |
failed = false, | |
resolveValues = Array.prototype.slice.call( arguments ), | |
length = resolveValues.length, | |
// the count of uncompleted subordinates | |
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, | |
// the master Deferred. If resolveValues consist of only a single Deferred, just use that. | |
deferred = remaining === 1 ? subordinate : jQuery.Deferred(), | |
// Update function for both resolve and progress values | |
updateFunc = function( i, contexts, values ) { | |
return function( value ) { | |
contexts[ i ] = this; | |
values[ i ] = arguments.length > 1 ? Array.prototype.slice( arguments ): value; | |
if ( values === progressValues ) { | |
deferred.notifyWith( contexts, values ); | |
} else if ( !( --remaining ) ) { | |
if(failed){ | |
deferred.rejectWith( contexts, values ); | |
} else { | |
deferred.resolveWith( contexts, values ); | |
} | |
} | |
}; | |
}, | |
progressValues, progressContexts, resolveContexts; | |
// add listeners to Deferred subordinates; treat others as resolved | |
if ( length > 1 ) { | |
progressValues = new Array( length ); | |
progressContexts = new Array( length ); | |
resolveContexts = new Array( length ); | |
rejectContexts = new Array( length ); | |
for ( ; i < length; i++ ) { | |
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { | |
resolveValues[ i ].promise() | |
.done( updateFunc( i, resolveContexts, resolveValues ) ) | |
.fail( function(){failed = true} ) | |
.fail( updateFunc( i, resolveContexts, resolveValues ) ) | |
.progress( updateFunc( i, progressContexts, progressValues ) ); | |
} else { | |
--remaining; | |
} | |
} | |
} | |
// if we're not waiting on anything, resolve the master | |
if ( !remaining ) { | |
deferred.resolveWith( resolveContexts, resolveValues ); | |
} | |
return deferred.promise(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment