i have 3 functions and in each function i have a AJAX call which is synchronous in nature.
function()
{
a();
b();
c();
}
a()
{
ajaxGet(globals.servicePath + '/Demo.svc/GetDemoList/' + sessionStorage.SessionId,function(data, success) {}, '', {async: false}, false);
}
similarly for b() and c().
now i want to wait for the execution of these calls and then proceed with the other operations since those operations are based on the result i get here. how can i get this done?
i have 3 functions and in each function i have a AJAX call which is synchronous in nature.
function()
{
a();
b();
c();
}
a()
{
ajaxGet(globals.servicePath + '/Demo.svc/GetDemoList/' + sessionStorage.SessionId,function(data, success) {}, '', {async: false}, false);
}
similarly for b() and c().
now i want to wait for the execution of these calls and then proceed with the other operations since those operations are based on the result i get here. how can i get this done?
Share Improve this question asked Apr 13, 2015 at 14:29 NikkiNikki 1372 gold badges3 silver badges17 bronze badges 11-
Do you have control over the code in
a()
,b()
orc()
? If so, return the promise from$.ajax
and use$.when
in your anonymous function. – Rory McCrossan Commented Apr 13, 2015 at 14:30 - 2 Look into jquery .promise.done – Moishe Lipsker Commented Apr 13, 2015 at 14:30
- blog.slaks/2015-01-04/async-method-patterns – SLaks Commented Apr 13, 2015 at 14:31
-
2
Never use
async: false
. Learn to work the way browsers intended (asynchronously) :) – iCollect.it Ltd Commented Apr 13, 2015 at 14:31 - If they're synchronous then you don't have to do anything special at all to wait for them. – James Montagne Commented Apr 13, 2015 at 14:33
1 Answer
Reset to default 15- A: never use
async: false
. That way leads to the dark side! - B: see A :)
One solution is the use the jQuery promises returned from Ajax calls.
If you want to know when all 3 are done (asynchronously in any order) use $.when()
:
function()
{
$.when(a(), b(), c()).done(function(){
// Now do something else
});
}
and get each method to the return the jQuery promise of the Ajax call:
function a()
{
return $.ajax(globals.servicePath + '/Demo.svc/GetDemoList/' + sessionStorage.SessionId,function(data, success) {}, ''...);
}
I mocked up some fake "ajax calls" using timers to show this:
JSFiddle: http://jsfiddle/TrueBlueAussie/rqq41Lg3/
If, for some reason, you want them to run sequentially, then fire your extra code, you can chain them with then
a().then(b).then(c).done(function(){
console.log("All done");
});
JSFiddle: http://jsfiddle/TrueBlueAussie/rqq41Lg3/1/