wait till functions with ajax calls finish executi

2020-06-30 04:48发布

问题:

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?

回答1:

  • 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.net/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.net/TrueBlueAussie/rqq41Lg3/1/