0

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.

8
  • read about callbacks stackoverflow.com/questions/9596276/… Commented Mar 6, 2014 at 18:20
  • I think you're missing the entire point of having callbacks. They exist because you don't want requests to block. Instead of using blocking code, you need to change your approach so that whatever needs the response will be called inside a callback. Commented Mar 6, 2014 at 18:20
  • put the print in the success call back of the ajax function (.done) Commented Mar 6, 2014 at 18:21
  • 2
    Well making 500 silmutanous requests can only bring you issues... Commented Mar 6, 2014 at 18:22
  • 1
    ...and sending out 500 XHR requests at once isn't a great idea. Why are you trying to cheat a poll in the first place? Commented Mar 6, 2014 at 18:22

3 Answers 3

4

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);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I didn't know function when and apply
3
$('#vote').click(function(e) {                                      
    // some code

    var requests = [];
    for(var i = 0; i < 500; i++){
        requests.push($.ajax({ ... }));
    }
    $.when.apply($, requests).then(function() {
        console.log('No of attempt :' + noOfattempt);       
        console.log('No of vote :' + noOfvotes);
        console.log('No of fail :' + noOffail); 
    });
});

EDIT Note that .when fires when all requests finish the job or one of them fails. If you want to fire a callback after all of requests finish (no matter whether there's an error or not), then try this:

var custom_when = function(reqs) {
    var def = $.Deferred(),
        counter = reqs.length;
    for (var i = 0; i < counter; i++) {
        reqs[i].always(function() {
            counter--;
            if (!counter) {
                def.resolve();
            }
        });
    }
    return def.promise();
};

and use it like that:

custom_when(requests).then(...);

9 Comments

What are noOfattempt, noOfvotes and noOffail ??? How do you update corresponding values?
Note that when using .then() it will be triggered right away if one of the promises is rejected (as in the ajax call fails).
@A.Wolff Who cares? These variables don't matter.
@freakish - That doesn't help much, I'm mistaken as well, as done only fires if they where all successful.
@adeneo indeed here then callback is equivalent to success callback
|
1

Move the log statements into .always and check that the noOfattempt is equal to the amount you tried.

.always(function() {
  noOfattempts++;
  if (noOfattempts === 500) {
    // we're done
  }
 })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.