JQuery的deferred.done立即执行predefined功能,但声明内无法正常工作无法正常、声明、功能、工作

2023-09-10 20:26:28 作者:赐你滚蛋

我的问题是一个奇怪的一个,因为在标题中描述。这里的code:

My problem is a weird one, as described in the title. Here's the code:

案例1:

    var first = $.ajax({ // about 500ms request
        url: myUrl
        success: function() { console.log(1); }
    });

    var second = $.ajax({ // about 200 ms request
        url: myUrl
        success: function() { console.log(2); }
    });


    $.when(first, second).done(function() { console.log(3); });

日志2,1,3,所有的好,正是我想要的。

Logs 2, 1, 3. All good, just what I wanted.

案例2:

    var first = $.ajax({ // about 500ms request
        url: myUrl
        success: function() { console.log(1); }
    });

    var second = $.ajax({ // about 200 ms request
        url: myUrl
        success: function() { console.log(2); }
    });

    function logthree() {
        console.log(3);
    }


    $.when(first, second).done(logthree());

日志3,2,1,这是一个问题。该logthree()函数应该只一次,第一和第二的决心执行。

Logs 3, 2, 1, which is a problem. The logthree() function should only execute once first and second resolve.

为什么会出现这种情况?如何使用第2种情况没有任何问题?

Why does this happen? How can I use Case 2 without any problems?

注:同样的事情发生,如果第一和第二是功能,它们返回$就

Note: same thing happens if first and second are functions and they return an $.ajax.

注:同样的事情发生,如果第一和第二都是$不用彷徨

Note: same thing happens if first and second are both $.get.

推荐答案

更​​改为:

$.when(first, second).done(logthree);

正在执行 logthree()并通过返回的结果为 .done()。你需要传递一个函数引用 .done()这仅仅是 logthree 没有括号。当您添加括号,即指示JS跨preTER立即执行。这是一个常见的​​错误。

You are executing logthree() and passing the return result to .done(). You need to pass a function reference to .done() which is just logthree without the parens. When you add parens, that instructs the JS interpreter to execute it immediately. This is a common mistake.