jQuery Promise在AJAX请求后无法正常工作。

9

我的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,然后再执行 Then 块。有任何想法为什么会这样?我甚至尝试实现一个自定义回调函数(在Stackoverflow上找到的标准示例),但仍然无法正常工作。


1
在返回承诺的函数调用上不应使用 $ .when。然后,您很快就会发现您的函数没有返回承诺 :-) - Bergi
2个回答

21

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

$.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调用完成时得到解决。由于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!");
});

当只有一个需要等待的promise时,没有理由使用$.when(),因为它只是多余的代码。 只有在你有多个需要等待的promise时,$.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(),因为当只有一个 promise 时不需要它。 - jfriend00
+1 表示承认 Promise 中没有魔法 :-) - Bergi

1

你需要一个符合 Promise 对象的函数 myFunc(),并且返回 null。

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

输出:Then block hit!

尝试

return $.getJSON("...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接