0

When I try to break parent loop from function with break - it gives the following error:

Uncaught SyntaxError: Illegal break statement

Here's the relevant part of the code:

for (var i = 0; i < filesLength; i++) {
        myFunc(arg1, arg2, i);
    }


function myFunc (arg1, arg2, i) {
    var qr = "param1="+arg1+"&param2="+arg2;
    getParam = new XMLHttpRequest();
    getParam.open("POST", "file.php");
    getParam.send(qr);

    getParam.onreadystatechange = (function(getParam){
        return function() {
            if(getParam.readyState == 4){
                var res = getParam.responseText;
                if (res == '') {
                    // do something...
                    break; << THIS ONE
                }
            }
        }
    })(getParam);
}
3
  • 1
    what about return false? Commented Sep 30, 2014 at 19:48
  • 5
    It's asynchronous, so by the time the ajax call has completed, it's way to late to break anything. Commented Sep 30, 2014 at 19:48
  • I tried return false, it did not cut it. Commented Sep 30, 2014 at 19:49

1 Answer 1

6

Your loop has long, long since finished by the time you hit your break statement because the Ajax calls are asynchronous. The function assigned to onreadystatechange gets called in the future. Your for loop runs to completion and all the ajax calls have already been started by that time and they are going to then finish one by one as the responses are received by the system.

Perhaps you don't understand that by default an Ajax call is asynchronous. That means that the for loop starts each ajax call and continues running (and starts all of the ajax calls) while the ajax calls are processed by a server elsewhere. Then, some time later after your for loop has finished, the onreadystatechange callback gets called indicating one of the ajax calls has now completed. It is far too late at that point to stop the for loop as it has already finished.


If you explain better what you are trying to accomplish, we could help with a way to do that. If, for example, you want to send one ajax call, examine its results and then decide if you want to continue with more ajax calls, then you can't use the for loop to launch them all. You will have to iterate by doing one ajax call and then when that one completes, you decide based on its results in the completion callback whether to call the next one and so on.

Sign up to request clarification or add additional context in comments.

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.