如果函数返回 true 或 false,我正在寻找一种更好的方法来重试
function foo() { //
var tabList = window.content.document.getElementById('compTabs') // this might be null if page is not loaded and further code wont work
if (!tabList) { // stop here if tab list is null
return false;
}
// continue and finish function
}
// this is a loop that will go trough an array and this check needs to happen for each element of the array
for (var i; i < loopLenght; i++) {
// This is the actual code nothing else happens here.
if ( !foo() ) {
// try again
if ( !foo() ) {
// try one more time
if ( !foo() ) {
console.log('Failed')
}
}
}
// a lot more code coming here that should only run one per iteration
}
我只是在寻找一种更好、更简洁的方式来编写上面的代码。
最佳答案
var retries = 5;
var success = false;
while (retries-- > 0 && !(success = foo())) {}
console.log(success);
在这里,
retries--
每次循环迭代都会倒计时,success = foo()
执行 foo()
并将结果保存到 success
.如果
retries
点击0
或 success
变成 true
,循环停止。不需要循环体。警告:如果
foo()
这将不起作用是一个异步函数。
关于javascript - JS Retry函数多次看是否返回true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36329792/