JQuery deferred.done executes a predefined function instantly, but does not declare a function inside
My problem is weird as the title says. Here's the code:
Case 1:
var first = $.ajax({ // about 500ms request
url: myUrl
success: function() { console.log(1); }
});
var second = $.ajax({ // about 200 ms request
url: myUrl
success: function() { console.log(2); }
});
$.when(first, second).done(function() { console.log(3); });
Logs 2, 1, 3. Everything is fine, just what I wanted.
Case 2:
var first = $.ajax({ // about 500ms request
url: myUrl
success: function() { console.log(1); }
});
var second = $.ajax({ // about 200 ms request
url: myUrl
success: function() { console.log(2); }
});
function logthree() {
console.log(3);
}
$.when(first, second).done(logthree());
Logs 3, 2, 1, which is the problem. The logthree () function should only run after the first and second permission.
Why is this happening? How can I use case 2 without any problem?
Note. The same happens if the first and second functions and they return $ .ajax.
Note. The same happens if the first and second are $ .get.
source to share
Change to:
$.when(first, second).done(logthree);
The logthree()
return result is executed and passed to .done()
. You need to pass a reference to the function to .done()
, which is just logthree
no boyfriends. When you add parens, this instructs the JS interpreter to execute it immediately. This is a common mistake.
source to share