jQuery.when 理解

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5280699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:53:21  来源:igfitidea点击:

jQuery.when understanding

jqueryajaxjquery-deferred

提问by Ashish

I am trying to use the jQuery.whento fire two ajaxrequests and then call some function after the two requests have completed. Here's my code:

我正在尝试使用jQuery.when来触发两个ajax请求,然后在两个请求完成后调用一些函数。这是我的代码:

var count = 0;
var dfr;

var showData = function(data) {
    dfr.resolve();
    alert(count);
   // Do something with my data data received
};

var method1 = function() {
    dfr = $.Deferred();

    return $.ajax('localhost/MyDataService/DataMethod_ReturnsData', {
        dataType: "jsonp",
        jsonp: "$callback",
        success: showData
    });
};

var method2 = function() {
    return $.ajax('localhost/MyDataService/DataMethod_ReturnsCount', {
        dataType: "jsonp",
        jsonp: "$callback",
        success: function(data) {
            count = data.d.__count;
        }
    });
};

$.when(method1(), method2())
    .then(showData());

However this is not working as expected. Ajax call in method1will return data which is to be used in showData()and Ajax call in method2will return count which is to be assigned to var count and later used in showData().

然而,这并没有按预期工作。在Ajax调用method1返回它是使用数据showData()和Ajax调用的method2返回计数将被分配给VAR计数,后来在使用showData()

But when I fire the above code, method1gets called and then method2and then showDataleaving the data in showDataas 'undefined'. How can I achieve this via $.whenwhich as far as I know proceeds only when both functions returning $.promiseare executed. I want that both the ajax calls should be called in parallel and later results be displayed based on results from both calls.

但是,当我火上面的代码中,method1被调用,然后method2showData离开数据showData作为'undefined'。我怎样才能实现这$.when一点,据我所知,只有在$.promise执行返回的两个函数时才会进行。我希望应该并行调用两个 ajax 调用,并根据两个调用的结果显示稍后的结果。

回答by Guillaume86

function showData(data1, data2) {
    alert(data1[0].max_id);
    alert(data2[0].max_id);
}

function method1() {
    return $.ajax("http://search.twitter.com/search.json", {
        data: {
            q: 'ashishnjain'
        },
        dataType: 'jsonp'
    });
}

function method2() {
    return $.ajax("http://search.twitter.com/search.json", {
        data: {
            q: 'ashishnjain'
        },
        dataType: 'jsonp'
    });
}

$.when(method1(), method2()).then(showData);?

Here's a working jsFiddle

这是一个有效的jsFiddle

回答by Matt Ball

The problem is that you're passing showData()to then(), not showData. You should pass a reference to a function to .then():

问题是你传递的showData()then(),而不是showData。您应该将一个函数的引用传递给.then()

$.when(method1(), method2())
    .then(showData);

or

或者

$.when(method1(), method2())
    .then(function () {
        showData();
    });

Edit

编辑

I've put together a working demo. Part of the problem (at least in the code fragment you posted) was that there was no callback function named $callback. Part of the problem was the $in the callback name '$callback'.

我已经整理了一个工作演示。部分问题(至少在您发布的代码片段中)是没有名为$callback. 部分问题出$在回调名称中'$callback'

So, remove the jsonp: '$callback'ajax option, so that jQuery defaults to a callback function named callback, anddefine a function with that name, and it all works.

因此,删除jsonp: '$callback'ajax 选项,以便 jQuery 默认为名为 的回调函数callback使用该名称定义一个函数,一切正常。

回答by Haresh Vidja

I have little bit modified your code and made simpler to understand... i haven't test it please try it

我对您的代码进行了一些修改并使其更易于理解...我还没有测试过请尝试一下

var count = 0;
function countResponse(data) {
    count++;
    if(count==2)
    {
        // Do something after getting responce from both ajax request
    }
};

var method1 = function() {
    return $.ajax('localhost/MyDataService/DataMethod_ReturnsData', {
        dataType: "jsonp",
        jsonp: "$callback",
        success: function(data) {
            countResponse(data)
        }
    });
};

var method2 = function() {
    return $.ajax('localhost/MyDataService/DataMethod_ReturnsCount', {
        dataType: "jsonp",
        jsonp: "$callback",
        success: function(data) {
            countResponse(data)
        }
    });
};