Javascript在回调函数中破坏for循环 [英] Javascript breaking a for loop inside a callback function
问题描述
我有如下代码:
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;
}
});
}
要点是 test() 函数是一个发出 XHR 请求的函数(它实际上是 Appcelerator Titanium 平台的 API,所以我无法控制它)并且我正在循环调用测试函数.我需要中断 onerror 函数上的循环,但我收到一条错误消息,指出中断不在循环或 switch 语句中.我该如何重写?
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?
推荐答案
如果您的代码示例确实代表了一些实际代码(即所有处理都在同一个事件循环滴答中完成),您可以执行以下操作:
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;
}
}
否则,如果有一些异步完成,你必须顺序调用test
,而不是并行调用.例如,
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);
这篇关于Javascript在回调函数中破坏for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!