$.when.apply for many promises
according to http://stackoverflow.com/questions/14777031/what-does-when-apply-somearray-do this should not do the alert until all promises are resolved. but this modified example from user3388213 resolves the always after 2 seconds
by logankd
JavaScript
// according to http://stackoverflow.com/questions/14777031/what-does-when-apply-somearray-do this should not do the alert until all promises are resolved.
// but this modified example from user3388213 resolves the always after 2 seconds
// the first reject will fire the always, but not the .then
var data = [1,2,3,4]; // the ids coming back from serviceA
var processItemsDeferred = [];
processItemsDeferred.push($.Deferred());
processItemsDeferred.push($.Deferred());
for(var i = 0; i < data.length; i++){
processItemsDeferred.push(processItem(data[i]));
}
// .always will fire as soon as the first deferred is rejected
//processItemsDeferred[0].reject();
// .always will not fire if it is resolved
//processItemsDeferred[0].resolve();
// .then doesn't fire if this isn't resolved or rejected
//processItemsDeferred[1].resolve();
$.when.apply($, processItemsDeferred)
.then(function(){ alert('then'); })
.always(function(){ alert('always') });
processItemsDeferred[0].resolve();
function processItem(data) {
var dfd = $.Deferred();
console.log('called processItem');
//in the real world, this would probably make an AJAX call.
setTimeout(function() { dfd.resolve(); }, 2000);
return dfd.promise();
}
function everythingDone(){
alert('processed all items');
}