I am trying to use jQuery.when to run two ajax requests and then call some function after two requests have completed. Here is 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 does not work properly. An Ajax call in method1 will return the data that will be used in showData() , and an Ajax call in method2 will return the account that should be assigned to the var account, and then used in showData() .
But when I run the above code, method1 is method1 , then method2 , and then showData leaving the data in showData as 'undefined' . How can I achieve this with $.when , which, as far as I know, is only executed when both functions returning $.promise . I want both ajax calls to be called in parallel, and subsequent results are displayed based on the results of both calls.
jquery ajax jquery-deferred
Ashish Mar 12 2018-11-11T00: 00Z
source share