ajax $.when,ajax - jQuery.when understanding - Stack Overflow

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

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 method1 will return data which is to be used in showData() and Ajax call in method2 will return count which is to be assigned to var count and later used in showData().

But when I fire the above code, method1 gets called and then method2 and then showData leaving the data in showData as 'undefined'. How can I achieve this via $.when which as far as I know proceeds only when both functions returning $.promise are executed. I want that both the ajax calls should be called in parallel and later results be displayed based on results from both calls.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值