Skip to content Skip to sidebar Skip to footer

Alternative To Async: False Ajax

I loop through an array running an ajax request for each. I need the requests to happen in order, so i can pick up the last request and run a function on success. at the moment im

Solution 1:

You can use a local function for running the ajax call and in each successive success handler, you can kick off the next ajax call.

function runAllAjax(array) {
    // initialize index counter
    var i = 0;

    function next() {
        var id = array[i].id;
        var title = array[i].title;
        $.ajax({
            async: true,
            url: 'url here',
            success: function(){
                ++i;
                if(i >= array.length) {
                    // run function here as its the last item in array
                } else {
                    // do the next ajax call
                    next();
                }

            }
        });
    }
    // start the first one
    next();
}

Updating this answer in 2016 with an option that uses promises. Here's how you run the requests in series:

array.reduce(function(p, item) {
    return p.then(function() {
        // you can access item.id and item.title here
        return $.ajax({url: 'url here', ...}).then(function(result) {
           // process individual ajax result here
        });
    });
}, Promise.resolve()).then(function() {
    // all requests are done here
});

Here's how you run them in parallel, returning all the results:

var promises = [];
array.forEach(function(item) {
    // you can access item.id and item.title here
    promises.push($.ajax({url: 'url here', ...});
});
Promise.all(promises).then(function(results) {
    // all ajax calls done here, results is an array of responses
});

Solution 2:

You can put your AJAX code in a separate function and whenever a request finishes it can call this method and pass its identity which will be incremented for the next request.


Solution 3:

Try $.when()

var requests = $.map(array, function (i, item) {
    return ajax_request(item.id, item.title, i);
});
$.when.apply($, requests).done(function(){
    $.each(arguments, function(i, params){
        var data = params[0];
        //do your stuff
    })
})

function ajax_request(id, title, i) {
    return $.ajax({
        async: false,
        url: 'url here'
    })
}

Post a Comment for "Alternative To Async: False Ajax"