Run two functions with Ajax calls sequentially

前端 未结 5 1706
难免孤独
难免孤独 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:30

    Because the ajax calls are asynchronous, you will need to manually sequence the ajax calls if you want the second one not to start until the first one is done.

    Promises are uniquely suited for serializing asynchronous operations and they can make it quite simple. Fortunately, jQuery has promises built in and every Ajax operation already returns a promise that can be used for this:

    $.ajax(...).then(function(result1) {
        // make 2nd ajax call when the first has completed
        return $.ajax(...);
    }).then(function(result2) {
        // success of both ajax calls here
    }, function(err) {
        // error here
    });
    

    Or, if you make a() and b() both return the jQuery ajax promises from their ajax calls, then you can just do this:

    a().then(b);
    

    And, c() could just be:

    function c() {
        return a().then(b);
    }
    

    So, if you want to make a function call to contain both these Ajax calls without a() and b(), you should have it return a promise:

    function c() {
        return $.ajax(...).then(function(result1) {
            // make 2nd ajax call when the first has completed
            return $.ajax(...);
        })
    }
    

    And, you can then call c() like this:

    c().then(function(result) {
        // success here
    }, function(err) {
        // error here
    });
    

    Here's an example of a function that returns an Ajax promise:

    function test() {
        return $.ajax("http://www.test.com/api/test");
    }
    

    Now, that you've added your actual ajax code, you can just add a return:

    function a(){ 
        return $.ajax({
            url: "url_a",
            type: "post",
            dataType: "html",               
            cache: false
        });   
    }
    
    function b(){ 
        return $.ajax({
            url: "url_b",
            type: "post",
            dataType: "html",               
            cache: false
        });   
    }
    
    function c() {
        return a().then(b);
    }
    

提交回复
热议问题