I am trying to use $.when(some function).then(some function)
in jQuery to force a callback function to wait until the code in $.when()
finishes first.
Here is my function.
function activateFirstTab(callback) {
console.log('started activateFirstTab');
console.log('Total groups found: '+ $('.functionParameterGroup').length);
$.when(function () {
$('.functionParameterGroup').each(function () {
//Activate the first tab "which is the default"
var first = $(this).find('ul > li:first');
first.addClass('active');
var contentId = first.data('contentid');
$(contentId).addClass('in active');
console.log('finished when logic in activateFirstTab');
});
}).then(function () {
// Make sure the callback is a function
if (typeof callback === "function") {
// Call it, since we have confirmed it is callable
callback();
}
});
console.log('finished activateFirstTab');
}
In the console I get the following messages
started activateFirstTab
Total groups found: 2
finished activateFirstTab
but I never get the message from the block inside $.when()
I am expecting the output to be this
started activateFirstTab
Total groups found: 2
finished when logic in activateFirstTab
finished when logic in activateFirstTab
finished activateFirstTab
Why the code inside $.when()
is not being executed?
How can I make it execute it? what mistake am I making?
答案 0 :(得分:1)
You do not call the function within $.when()
, also note the anonymous function passed to $.when()
does not return a promise; though any type of parameter can be passed to $.when()
function fn(callback) {
$.when(function dfd(callback) {
$.each([1, 2, 3], function(i, value) {
console.log(value)
});
return "dfd complete"
}() /* invoke `dfd` function */ )
.then(function(data) {
// Make sure the callback is a function
if (typeof callback === "function") {
// Call it, since we have confirmed it is callable
callback(data);
}
})
}
fn(function(args) {
alert(args)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>