Run two functions with Ajax calls sequentially

前端 未结 5 1674
难免孤独
难免孤独 2021-01-26 09:52

I have two functions which has ajax calls inside them.

function a(){
    ajaxCall_A();
}
function b(){
    ajaxCall_B();
}

And I

5条回答
  •  佛祖请我去吃肉
    2021-01-26 10:25

    Simply use jQuery.when() & done() with Deferred:

        function a() {
            var deferred = $.Deferred();
    
            $.ajax({
            url: "url_a",
            type: "post",
            dataType: "html",               
            cache: false,
            success: function(data){             
                deferred.resolve(data);
            },
            error:function(){             
               deferred.resolve("Error from a()");
           }   
          });  
          return deferred.promise();
        }
        function b() {
            var deferred = $.Deferred();
    
            $.ajax({
            url: "url_b",
            type: "post",
            dataType: "html",               
            cache: false,
            success: function(data){             
                deferred.resolve(data);
            },
            error:function(){             
               deferred.resolve("Error from b()");
           }   
          }); 
    
            return deferred.promise();
        }
    
        function c()
        {
            $.when(
                a(),
                b()
           )
          .done(function ( v1, v2 ){
          //Do your work - v1 and v2 are resolved value from a() and b() 
          });       
        }
    

提交回复
热议问题