jQuery callback for multiple ajax calls

后端 未结 14 1654
夕颜
夕颜 2020-11-22 09:18

I want to make three ajax calls in a click event. Each ajax call does a distinct operation and returns back data that is needed for a final callback. The calls themselves ar

14条回答
  •  逝去的感伤
    2020-11-22 09:39

    Ok, this is old but please let me contribute my solution :)

    function sync( callback ){
        syncCount--;
        if ( syncCount < 1 ) callback();
    }
    function allFinished(){ .............. }
    
    window.syncCount = 2;
    
    $.ajax({
        url: 'url',
        success: function(data) {
            sync( allFinished );
        }
    });
    someFunctionWithCallback( function(){ sync( allFinished ); } )
    

    It works also with functions that have a callback. You set the syncCount and you call the function sync(...) in the callback of every action.

提交回复
热议问题