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?
Maybe you can make the 'onload' callback recursive?
Meaning, you just call the 'test' method inside the 'onload' handlerr, this would also mean you fire all requests in order instead of all at the same time.
I take the answer of penartur, but I modified without the "break":
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:
Otherwise, if there is something asynchronous done, you have to call
test
sequentially, and not in parallel. For example,Bit hacky maybe but one could do something like this with a handler function.
Didn't test this but maybe you could bind function to scope in call even?
You cannot break the loop inside test() function. I think the best solution in this case would be to throw an exception inside test() function, then catch it in the loop and break.
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.