Maintain order of requests when making several ajax callbacks

后端 未结 4 611
名媛妹妹
名媛妹妹 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:14

    The answer to this ended up being a jQuery plugin called ajaxManager. This did exactly what I needed:

    https://github.com/aFarkas/Ajaxmanager

    0 讨论(0)
  • 2021-01-05 06:20

    Well the results can come back in any undefined order, they are asynchronous and subject to the vagaries of the internet and servers.

    What you can do is deal with the problem in the same way TCP does over UDP. You use sequence identifiers.

    Keep a sequence identifier going, and increment it every time you send out a request. As requests come back, check them off in order and only process them as they come in. Keep a list of what has returned with the data in order, and have a routine fire to check that list after each update to it. When the first expected is in, it should process the whole list down to the first gap.

    Bare in mind that you could lose a request, so a suitable timeout before you ignore a given sequence identifier would be in order.

    0 讨论(0)
  • 2021-01-05 06:29

    I'll be taking a stab in the dark with this one but it might help. Maybe you could create a global buffer array and then whenever the AJAX returns you can add the result to the buffer. You could then set up a timer that, when triggered, will check the contents of the buffer. If they are in order it will output it accordingly.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题