Synchronous Ajax with jQuery

I have a web application that makes up a ton of requests $.post(). The server should receive them in the order in which they were created. To guarantee this, I first thought that I would make my own queue, which was canceled and fired the next Ajax call after the previous one ended.

Then I saw a parameter there async:falsethat you can use with $.ajax().

I changed all my usage requests $.ajax({ async: false, ... }), but when I track them in Firebug, the requests are not sent one by one, each subsequent request is launched after the last one received a response.

What does it mean async? How can I connect my Ajax so that it runs at a time, and the next one at the end of the last (received answer)?

+3
source share
1 answer

Instead of using it, async:falseyou can create a function that is recursively called from a callback.

function sendReq( arr ) {
    var current = arr.shift(); // Remove the first item from the Array.
    $.ajax({
        url: current.url,      // Use the url from the first item.
        success: function( dat ) {
            current.func( dat );  // Call the function of the first item.
            if( arr.length )      // If there are items left in the Array,
               sendReq( arr );    //     make a recursive call, sending
        }                         //     the remainder of the array.
    });
}

// Ordered collection of requests to be made.
var req_set = [
    {url:'someurl', func:function( dat ) { /*do something with dat*/ }},
    {url:'anotherurl', func:function( dat ) { /*do something with dat*/ }},
    {url:'someother', func:function( dat ) { /*do something with dat*/ }}
];
 // Start the first call, sending the entire set.
sendReq( req_set );

So basically:

  • Make an array of objects containing the necessary elements for queries.
  • Make a function that takes an array.
  • The function removes the first element from the array and uses this object to populate the request properties.
  • In the callback, after calling the function for this element, make a recursive call to the function, passing the rest of the array.
  • , .
+7

Source: https://habr.com/ru/post/1779701/


All Articles