Javascript breaking a for loop inside a callback function

Viewed 17830

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?

6 Answers

I take the answer of penartur, but I modified without the "break":

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){
            console.log('stop');
        }
    });
}

f(0);
Related