Maintain order of requests when making several ajax callbacks

后端 未结 4 644
名媛妹妹
名媛妹妹 2021-01-05 05:45

I\'m looping through several items and making an ajax request for each of them (using jQuery). I want them to execute independently, but populate into the DOM in the order

4条回答
  •  我在风中等你
    2021-01-05 06:32

    You could send all the success result objects to a queue. Have an index that was sent with the original request, and continually check that queue for the next index.

    But generally browsers only allow two simultaneous ajax requests, so it might be worth it to just send the next ajax request on success of the previous request.

    Here's a start at the code:

    var results = {}, lastProcessedIndex = 0;
    var totalLength = $('a.myselector').each(function(el, index){
        $.ajax({
            url: $(this).attr('href'),
            success: function(result){
                results[index] = result; // add to results object
            }
        });
    }).length;
    
    var intervalId = setInterval(function(){
        if(results[lastProcessedIndex]){
            // use object
            lastProcessedIndex++;
        }
        else if(totalLength == lastProcessedIndex){
            clearInterval(intervalId); 
        }
    }, 1000); // every 1 second
    

提交回复
热议问题