我認爲這個問題需要一個更完整的解釋。
$.when()
沒有什麼神奇的力量可以知道什麼時候你把它放入其中的一些功能恰好完成了。只有當您傳遞$.when()
一個或多個承諾時纔會與異步操作一起工作,這些承諾在底層異步操作完成時自行解析。
所以,在你的代碼:
myFunc = function() {
$.getJSON("./rest/api/some/url", function(json, textStatus) {
console.log("AJAX call hit!");
});
};
$.when(myFunc()).then(function() {
console.log("Then block hit!");
});
myFunc()
是什麼意思undefined
回來,所以你在本質上做的:
myFunc();
$.when(undefined).then(function() {
console.log("Then block hit!");
});
當你不傳遞任何承諾$.when()
,它只是立即解決(因爲它沒有什麼可以等待)。
取而代之,您需要確保myFunc()
返回一個在Ajax調用完成時解析的promise。由於jQuery的$.getJSON()
已經返回了這樣的承諾,所有你需要做的就是回到這個承諾是這樣的:
var myFunc = function() {
return $.getJSON("./rest/api/some/url", function(json, textStatus) {
console.log("AJAX call hit!");
});
};
$.when(myFunc()).then(function() {
console.log("Then block hit!");
});
當然,如果只有一個承諾等待,沒有理由使用因爲它只是額外的代碼而已。當你有多個承諾要等待時,$.when()
確實只會增加價值。所以,你可以這樣做:
var myFunc = function() {
return $.getJSON("./rest/api/some/url", function(json, textStatus) {
console.log("AJAX call hit!");
});
};
myFunc().then(function() {
console.log("Then block hit!");
});
你不應該在返回promise的函數調用中使用'$ .when'。那麼你很快就會發現你的函數沒有返回一個承諾:-) – Bergi