Multiple ajax requests are executed sequentially

       If you encounter multiple ajax requests during work, you need to make data requests in order and ensure that the data is returned in order in the order of the requests. So you need to wrap the request. The case when method that comes with jquery can only guarantee that the request is sent in order, but it cannot guarantee that the requested data is returned in order.

The specific processing method is as follows:

1. Create an array to store ajax requests,

2. Create a function that executes the ajax request, execute the first ajax function in the array in the function, delete the ajax function after the request returns, and then judge the length of the array. If the length of the array is greater than zero, it means that there are still requests that have not been completed , continue to execute the ajax function. In fact, it is handled by the principle of recursion.

example:

var categorieList = [
        {
            categoryId: 1,
            id: 11151, //for testing
            type: "Technology"
        },{
            categoryId: 2,
            id: 11164, //for testing
            type: "ability"
        },{
            categoryId: 3,
            id: 11146, //for testing
            type: "Product"
        }
    ];
    if( typeof(result.label) != "undefined" && !isBlank(result.label) ){
        var ajaxes = []; //Queue for storing parameter objects
        for(var i=0; i< categorieList.length; i++){
            ajaxes.push( {categorieId: categorieList[i].categorieId, type: categorieList[i].type, result: result } );
        }

   Create the function that performs the ajax request:

var  executeAjax = function(){
            if(ajaxes.length < 1){
                return;
            }
            var params = ajaxes[0];
            $.ajax({
                 type:  .....
                 success: function(response){
                       ...
                       // delete the first request in the queue
                    ajaxes.shift();
                    //If there are still requests in the queue, execute the executeAjax function recursively until the queue is empty
                    if( ajaxes.length > 0){
                        executeAjax();
                    }
                 }
            });
};
executeAjax(); //Execute the function request.

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327013026&siteId=291194637
Recommended