简体   繁体   中英

how to break javascript for-loop from nested function

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM