JQuery deferred.done executes predefined function instantly, but not function declared inside

和自甴很熟 提交于 2020-01-05 08:00:33

问题


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

Case 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); });

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

Case 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());

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

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.


回答1:


Change to:

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

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.




回答2:


Try this..

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



来源:https://stackoverflow.com/questions/26575979/jquery-deferred-done-executes-predefined-function-instantly-but-not-function-de

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!