等到带有ajax调用的函数在jquery中完成执行

等到带有ajax调用的函数在jquery中完成执行

问题描述:

我有3个函数,在每个函数中我都有一个AJAX调用,它本质上是同步的。

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);
}

类似于b()和c()。

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?


  • 答:永远不要使用 async :false 。这样就会导致黑暗的一面!

  • B:见A:)

    • A: never use async: false. That way leads to the dark side!
    • B: see A :)
    • 一个解决方案是从Ajax调用返回的jQuery promise的使用。

      One solution is the use the jQuery promises returned from Ajax calls.

      如果你想知道所有3个完成的时间(以任何顺序异步),请使用 $ .when()

      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
  });
}

并获取每个方法以返回Ajax调用的jQuery承诺:

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) {}, ''...);
}

我使用计时器模拟了一些虚假的ajax调用来显示:

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/