Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript breaking a for loop inside a callback function

I have code like the following:

function test(obj) {

    if(//some conditon) {
        obj.onload();
    }else{
        obj.onerror();
    }
}


for(var i=0;i<4;i++){   

    test({
        onload:function(e){          
            //some code to run
        },
        onerror:function(e){
            break;
        }


    });
}

The gist is the test() function is a function to make an XHR request (it is actually an API of the Appcelerator Titanium platform so I have no control over it) and I'm looping something to call the test function. I need to break the loop on the onerror function, but I get an error saying the break is not inside a loop or switch statement. How can I rewrite this?

like image 295
eirikrl Avatar asked Aug 07 '12 09:08

eirikrl


2 Answers

If your code sample does represent some actual code (i.e. all the processing is done in the same event loop tick), you may do the following:

function test(obj) {

    if (some_condition) {
        return obj.onload();
    } else {
        return obj.onerror();
    }
}

var result;
for(var i=0; i<4; i++){   

    result = test({
        onload:function(e){          
            //some code to run
            return true;
        },
        onerror:function(e){
            return false;
        }


    });

    if (!result) {
        break;
    }
}

Otherwise, if there is something asynchronous done, you have to call test sequentially, and not in parallel. For example,

function test(obj) {
    doSomeAjaxRequest(arguments, function (err, result) {
        if (some_condition) {
            obj.onload();
        } else {
            obj.onerror();
        }
    });
}

var f = function (i) {
    if (i >= 4) return;
    test({
        onload:function(e){          
            //some code to run
            f(i+1);
        },
        onerror:function(e){
            break;
        }
    });
}

f(0);
like image 83
penartur Avatar answered Sep 27 '22 22:09

penartur


Not possible. A for loop is a synchronous procedure while an Ajax request is not. That means when the onerror callback happens, the for loop is already done executing.

As an alternative you could introduce a check into your onsuccess handler which confirms no errors have happened yet.

var errorOccured = false;
for(var i=0;i<4;i++){   

test({
    onload:function(e){   
        if(errorOccured) return;
        //some code to run
    },
    onerror:function(e){
        errorOccured = true;
    }


});
}
like image 33
just.another.programmer Avatar answered Sep 27 '22 21:09

just.another.programmer