简体   繁体   English

在所有先前的ajax调用完成后触发ajax调用

[英]Fire ajax call after all the previous ajax calls have completed

Lets say I have functions like: 可以说我有如下功能:

function A(){
    func B();
    ajax call last;
}

func B(){
   if some condition1
       func C();
   if some condition2
       func D();
   if some condition3
       func E();
}

func C(){
     some ajax cal 1
}

func D(){
     ajax call 2
}

func E(){
     ajax call 3
}

My problem is ajax call last should be fired only when all the previous ajax calls have completed .ie ajax call 1 , 2 , 3. 我的问题是,仅当所有先前的ajax调用均已完成时才应触发ajax调用last,即ajax调用1、2、3。

If you're using jQuery then you have access to various calls based on a promise . 如果您使用的是jQuery,则可以基于promise来访问各种调用。 Calls to $.ajax return a promise that can be used to defer subsequent calls. 调用$.ajax返回一个promise ,可用于推迟后续调用。 See the documentation for the jQuery when call (docs here ). 调用when请参阅jQuery的文档( 此处为docs)。

Using when you can execute a function after a $.ajax call has completed. $.ajax调用完成后when执行函数when使用。 You can use the same technique for a single such call to $.ajax , or multiple calls. 您可以对$.ajax这样的单个调用或多次调用使用相同的技术。

I'm not sure based on your question how you want to chain the calls, but here's an attempt based on your code (untested but this should get you on the right track): 根据您的问题,我不确定您要如何链接这些呼叫,但这是根据您的代码进行的尝试(未经测试,但这应该可以使您走上正确的轨道):

func B()
{
    var callC = null;
    var callD = null;
    var callE = null;

    if (condition1)
        callC = $.ajax("/call/1");

    if (condition2)
        callD =  $.ajax("/call/2");

    if (condition3)
        callE =  $.ajax("/call/3");

    $.when(callC, callD, callE).then($.ajax("/call/last"));
}

.then will execute once the 3 AJAX calls have completed , regardless of their success or failure. .then将在3个AJAX调用完成后执行 ,无论它们成功与否。 Also look at .done if you only want to continue if all calls return success. 如果只想在所有调用都返回成功后继续,则还要查看.done

Try utilizing return , .then() 尝试利用return.then()

function A() {
    return B();
}

function B() {
   if (some_condition1) {
       return C();
   };
   if (some_condition2) {
       return D();
   };
   if (some_condition3) {
       return E();
   };
}

function C() {
     // some ajax call 1
     return $.ajax()
}

function D() {
     // ajax call 2
     return $.ajax()
}

function E() {
     // ajax call 3
     return $.ajax()
}

A().then(function() {
  // ajax call last;
  return $.ajax()
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM