问题
My problem is a weird one, as described in the title. 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. All good, 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 a problem. The logthree() function should only execute once first and second resolve.
Why does this happen? How can I use Case 2 without any problems?
Note: same thing happens if first and second are functions and they return an $.ajax.
Note: same thing happens if first and second are both $.get.
回答1:
Change to:
$.when(first, second).done(logthree);
You are executing logthree()
and passing the return result to .done()
. You need to pass a function reference to .done()
which is just logthree
without the parens. When you add parens, that instructs the JS interpreter to execute it immediately. This is a common mistake.
回答2:
Try this..
`$.when(first, second).done(logthree);
来源:https://stackoverflow.com/questions/26575979/jquery-deferred-done-executes-predefined-function-instantly-but-not-function-de