done立即执行predefined功能

done立即执行predefined功能

本文介绍了JQuery的deferred.done立即执行predefined功能,但声明内无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是一个奇怪的一个,因为在标题中描述。这里的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.

这篇关于JQuery的deferred.done立即执行predefined功能,但声明内无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:29