JS Retry函数多次查看它是否返回true

Tra*_*rax 4 javascript

我正在寻找一种更好的方法来重试函数是否返回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
}
Run Code Online (Sandbox Code Playgroud)

我只是在寻找一种更好,更干净的方法来编写上面的代码。

Tom*_*lak 7

var retries = 5;
var success = false;

while (retries-- > 0 && !(success = foo())) {}

console.log(success);
Run Code Online (Sandbox Code Playgroud)

在这里,retries--每次循环迭代都会递减计数,然后success = foo()执行foo()并将结果保存到中success

如果任一retries命中0success变为true,则循环停止。不需要循环体。

警告:如果foo()是异步功能,则将无法使用。