然后jQuery Promise在AJAX之后无法工作

我的Promise定义如下:

myFunc = function() { $.getJSON("./rest/api/some/url", function(json, textStatus) { console.log("AJAX call hit!"); }); }; $.when(myFunc()).then(function() { console.log("Then block hit!"); }); 

并在控制台中输出为:

 Then block hit! AJAX call hit! 

我需要AJAX call hit! 首先跟着Then block hit!

知道为什么会这样吗? 我甚至试图实现一个自定义回调函数(我在Stackoverflow上找到的标准示例),它仍然无法正常工作。

我认为这个问题需要更完整的解释。

$.when()没有神奇的力量知道什么时候你把它放在它的parens中的某些function正好完成。 当您传递$.when()一个或多个在底层异步操作完成时自行解决的promise时,它只适用于异步操作。

所以,在你的代码中:

 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()已经返回了这样的一个承诺,你所要做的就是像这样返回那个promise:

 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() ,因为它只是额外的代码阻碍了。 当你有多个承诺要等待时, $.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相容的对象functon myFunc()返回null

 $.when(null).then(function() { console.log("Then block hit!"); }); 

输出:然后阻止命中!

尝试

 return $.getJSON("...