[removed] wait for function in loop to finish executing before next iteration

前端 未结 2 497
無奈伤痛
無奈伤痛 2021-01-06 12:02
$(function() {
$(\"#submit\").click(function() {


for (var i=1; i<=14; i++)
{
        setID(i); 
        checkField(i);

}

if ($(\'#pass_fail\').val() != \"fail         


        
2条回答
  •  鱼传尺愫
    2021-01-06 12:55

    I'm assuming from your description of the issue that checkField() is making some sort of asynchronous Ajax call. If you truly want to serialize the calls to checkField() so the 2nd call is not made until the first has completed, then you need to change the structure and flow of your code in order to do that. The two common ways of doing so are either using a callback that indicates completion of a call to checkField() that triggers the next call to checkField() or the use of promises to accomplish something similar.

    Here's an example of the callback mechanism:

    $("#submit").click(function() {
        var i = 0;
        function next() {
            i++;
            if (i <= 14) {
                setID(i);
                checkField(i, next);
            } else {
                // all checkField operations are done now
                if ($('#pass_fail').val() != "fail") { 
                    //do something
                }
            }
        }
        next();
    });
    

    Then, checkField() would have to be modified to call the callback passed to it when it completes its asynchronous operation.


    If you're using jQuery to make the ajax operations inside of checkField, it would be fairly easy to use jQuery promises to solve this also.

提交回复
热议问题