Example on when to use: I want that after all promises are resolved, do something. For example every ajax request adds the ajax response data in an array. I want to make sure all data has been added before doing something else.
#1
// You can create an array of promises so that once all promises are resolved you can run your all done code.
var promises = []
;for (var i = 0; i < $total_files; i++){
/* $.ajax returns a promise*/
var request = $.ajax({
/* your ajax config*/
})
promises.push( request);}
$.when.apply(null, promises).done(function(){
alert('All done')})
#2
var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();
$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
console.log( v1 ); // v1 is undefined
console.log( v2 ); // v2 is "abc"
console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
});
d1.resolve();
d2.resolve( "abc" );
d3.resolve( 1, 2, 3, 4, 5 );
src: https://api.jquery.com/jQuery.when/
#3 (just copy-pasted my work in the bike booking system proj)
let promises = [];
//for each resource id..
resourceIds.forEach((id) => {
// use the resource id to get resource data
var promise = dataService.getResourcesDataById(id).then(resourceData => {
var jqxhr = $.getJSON(url, function (slots) {
//do something
}).fail((jqXHR, textStatus, errorThrown) => {
//do something
});
return jqxhr;//return promise
});
promises.push(promise);
});
$.when.apply(null, promises).done(function () {
//when all promises are resolved do something
})
.fail((jqXHR, textStatus, errorThrown) => {
//do something
});
https://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done