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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29607893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:46:53  来源:igfitidea点击:

wait till functions with ajax calls finish execution in jquery

javascriptjqueryajax

提问by Nikki

i have 3 functions and in each function i have a AJAX call which is synchronous in nature.

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

function()
{
  a();
  b();
  c();
}
a()
{
   ajaxGet(globals.servicePath + '/Demo.svc/GetDemoList/' + sessionStorage.SessionId,function(data, success) {}, '', {async: false}, false);
}

similarly for b() and c().

b() 和 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?

现在我想等待这些调用的执行,然后继续其他操作,因为这些操作是基于我在这里得到的结果。我怎样才能做到这一点?

回答by Gone Coding

  • A: never use async: false. That way leads to the dark side!
  • B: see A :)
  • 答:从不使用async: false。那样会导致黑暗面!
  • B: 见 A :)

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

一种解决方案是使用从 Ajax 调用返回的 jQuery 承诺。

If you want to know when all 3 are done (asynchronously in any order) use $.when():

如果您想知道所有 3 项何时完成(以任何顺序异步),请使用$.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:

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

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:

我用计时器模拟了一些假的“ajax 调用”来显示这一点:

JSFiddle:http://jsfiddle.net/TrueBlueAussie/rqq41Lg3/

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

如果出于某种原因,您希望它们按顺序运行,然后触发您的额外代码,您可以将它们链接起来 then

a().then(b).then(c).done(function(){
    console.log("All done");
});

JSFiddle:http://jsfiddle.net/TrueBlueAussie/rqq41Lg3/1/

JSFiddle:http : //jsfiddle.net/TrueBlueAussie/rqq41Lg3/1/