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

时间:2015-07-03 18:17:44

标签: 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 hit!
AJAX call hit!

首先需要AJAX call hit!,然后是Then block hit!

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

2 个答案:

答案 0 :(得分:15)

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

$.when()没有神奇的力量可以知道你把它放在其中的某些功能的时候发生了什么。当您传递$.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()已经返回了这样的承诺,你所要做的就是像这样返回这个承诺:

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!");
});

答案 1 :(得分:1)

你需要与promise相容的对象functon myFunc()返回null

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

输出:然后阻止命中!

尝试

return $.getJSON("...