Javascript jQuery承诺在AJAX之后不起作用
我的承诺定义如下:Javascript jQuery承诺在AJAX之后不起作用,javascript,jquery,ajax,promise,jquery-deferred,Javascript,Jquery,Ajax,Promise,Jquery Deferred,我的承诺定义如下: 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 hi
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调用命中代码>先是然后是block hit代码>
知道为什么会这样吗?我甚至尝试实现一个自定义回调函数(我在Stackoverflow上找到的一个标准示例),但它仍然不起作用。您需要promise compatible object functionmyFunc()
返回空值
$.when(null).then(function() {
console.log("Then block hit!");
});
输出:然后拦截命中
试一试
我认为这个问题需要更完整的解释
$.when()
没有神奇的能力知道你放在它的paren中的某个函数什么时候碰巧完成了。它仅在您传递$时适用于异步操作。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()
不返回任何内容,这意味着未定义
,因此您实际上在执行以下操作:
myFunc();
$.when(undefined).then(function() {
console.log("Then block hit!");
});
当您不向$传递任何承诺时(
),它会立即解析(因为它没有什么可等待的)
相反,您需要确保myFunc()
返回在Ajax调用完成时解析的承诺。由于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()
,因为这只是额外的代码阻碍$.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!");
});
添加了一个更好的方法,它甚至不使用$.when()
,因为只有一个承诺时不需要它。+1用于断言承诺中没有魔力:-)您不应该在返回承诺的函数调用上使用$。然后您很快就会发现您的函数没有返回承诺:-)
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!");
});