jQuery 承诺然后在 AJAX 之后不起作用

jQuery Promise then not working after 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!

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

您需要兼容 promise 的对象函数 myFunc() returns null

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

输出:然后方块命中!

尝试

return $.getJSON("...

我觉得这个问题需要更完整的解释。

$.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() return 什么都没有,这意味着 undefined,所以你本质上是在做:

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

当您不向 $.when() 传递任何承诺时,它会立即解析(因为它没有什么可等待的)。

相反,您需要确保 myFunc() return 是在 Ajax 调用完成时解决的承诺。由于 jQuery 的 $.getJSON() 已经 return 这样的承诺,您所要做的就是 return 这样的承诺:

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(),因为它只是额外的代码。 $.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!");
});