jQuery.when理解

Ash*_*ish 57 ajax jquery jquery-deferred

我试图使用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());
Run Code Online (Sandbox Code Playgroud)

但是这没有按预期工作.Ajax调用method1将返回要使用的数据,showData()并且Ajax调用method2将返回计数,该计数将分配给var count并稍后用于showData().

但是,当我触发上面的代码时,method1调用然后method2然后showData将数据保留showData为as 'undefined'.我怎么能实现这个$.when目的,据我所知,只有当两个函数返回$.promise都被执行时才会继续.我想要并行调用两个ajax调用,然后根据两个调用的结果显示后面的结果.

Gui*_*e86 69

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);?
Run Code Online (Sandbox Code Playgroud)

这是一个有效的jsFiddle


Mat*_*all 30

问题是,你传递showData()then(),不是showData.您应该将对函数的引用传递给.then():

$.when(method1(), method2())
    .then(showData);
Run Code Online (Sandbox Code Playgroud)

要么

$.when(method1(), method2())
    .then(function () {
        showData();
    });
Run Code Online (Sandbox Code Playgroud)

编辑

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

因此,删除jsonp: '$callback'ajax选项,以便jQuery默认为一个名为的回调函数callback,定义一个具有该名称的函数,这一切都有效.