use*_*703 5 javascript ajax jquery promise jquery-deferred
我的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!");
});
Run Code Online (Sandbox Code Playgroud)
并在控制台中输出为:
Then block hit!
AJAX call hit!
Run Code Online (Sandbox Code Playgroud)
我需要第AJAX call hit!一个,然后是Then block hit!.
知道为什么会这样吗?我甚至试图实现一个自定义回调函数(我在Stackoverflow上找到的标准示例),它仍然无法正常工作.
jfr*_*d00 16
我认为这个问题需要更完整的解释.
$.when()没有神奇的力量可以知道什么时候你把它放在它的parens中的某些功能.当您传递$.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!");
});
Run Code Online (Sandbox Code Playgroud)
myFunc()什么意思都没有返回undefined,所以你实际上在做:
myFunc();
$.when(undefined).then(function() {
console.log("Then block hit!");
});
Run Code Online (Sandbox Code Playgroud)
当你没有通过任何承诺时$.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!");
});
Run Code Online (Sandbox Code Playgroud)
当然,当只有一个承诺等待时,没有理由使用$.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!");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5012 次 |
| 最近记录: |