Search code examples
javascriptjqueryajaxblocking

Non-Blocking code Issue in javascript


I was trying to make a brute force poll voting script.

$('#vote').click(function(e) {                                      
    var noOfvotes = 0;
    var noOfattempt =0;
    var noOffail =0;

    for(var i =0 ; i<500;i++){
        $.ajax({
            url: 'http://www.example.com/survey/',
            type: 'POST',                   
            data: {poll: '123',
                   vote:"option3"                             
                  },
        })
            .done(function() {
                noOfvotes++;
            })
            .fail(function() {
                noOffail++;
            })
            .always(function() {
                noOfattempt++;
            });
    }
    //Result printing
    console.log('No of attempt :' + noOfattempt);       
    console.log('No of done :' + noOfvotes);
    console.log('No of fail :' + noOffail); 
});

The issue i faced is result printing is executed before these ajax requests completed.So out put was like this on console

No of attempt :0   
No of done :0
No of fail :0

But I need to get these lines executed after all Ajax requests finishes. How can I make a blocking code for this situation.


Solution

  • Stack the requests in an array and use $.when to determine when they are all done

    $('#vote').click(function (e) {
        var XHR         = [],
            noOfvotes   = 0,
            noOfattempt = 0,
            noOffail    = 0;
    
        for (var i = 0; i < 500; i++) {
            XHR.push(
                $.ajax({
                    url: 'http://www.example.com/polling/',
                    type: 'POST',
                    data: {
                        poll: '123',
                        vote: "option3"
                    },
                }).done(function () {
                    noOfvotes++;
                }).fail(function () {
                    noOffail++;
                }).always(function () {
                    noOfattempt++;
                })
            );
        }
    
        $.when.apply(undefined, XHR).done(function() {
            console.log('No of attempt :' + noOfattempt);
            console.log('No of vote :' + noOfvotes);
            console.log('No of fail :' + noOffail);
        });
    });