Reputation: 6924
Problem that I'm trying to solve: I want to have two arrays of ajax functions. One with topPriority that should run first, and another one with low priority that will start as soon as ALL of the topPriority calls are done.
However, this functions are not even called in the $.when
line. Am I using this correctly?
//Html:
<div id="foo">Hello World</div>
//CSS:
#foo{ border:1px solid red; padding:10px; display:none }
//Javascript:
// open your console!
function getData(){
return $.get('/echo/html/');
}
function showDiv(){
var dfd = $.Deferred();
$('#foo').fadeIn( 1000, dfd.resolve );
return dfd.promise();
}
var topPriorityFunctions = new Array();
topPriorityFunctions.push(showDiv);
topPriorityFunctions.push(getData);
$.when.apply($, topPriorityFunctions )
.then(function( ajaxResult ){
console.log('The animation AND the AJAX request are both done!');
// ‘ajaxResult’ is the server’s response
// start my lowPriorityTasks.
});
Here is the fiddle with all this code in order to be able to test it an modify it.
References: I tried to modify from the working example on this page in order to solve my problem.
Upvotes: 0
Views: 70
Reputation: 239581
$.when
does not accept or expect an array of functions, it expects an array of deferreds. You need to invoke your functions, and pass the promises in.
var topPriorityPromises = [];
topPriorityFunctions.push(showDiv());
topPriorityFunctions.push(getData());
$.when.apply($, topPriorityPromises ).then(function () {
// ...
If you simplify this and ignore the array/apply portions, you would be invoking when
this way, which is wrong:
$.when(showDiv, getData);
not this way, which is correct:
$.when(showDiv(), getData());
Upvotes: 3