javascript - JS Retry函数多次看是否返回true

标签 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
}

我只是在寻找一种更好、更简洁的方式来编写上面的代码。

最佳答案

var retries = 5;
var success = false;

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

console.log(success);

在这里,retries--每次循环迭代都会倒计时,success = foo()执行 foo()并将结果保存到 success .

如果 retries点击0success变成 true ,循环停止。不需要循环体。

警告:如果 foo() 这将不起作用是一个异步函数。

关于javascript - JS Retry函数多次看是否返回true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36329792/

相关文章:

javascript - 如何在 AngularJS 的 ng-init 中使用三元?

javascript - RxJS - 您的平台不支持 Array.observe

javascript - 在 vb.net 中使用 javascript hide()/show()

javascript - 为公共(public)共享保存值状态(添加到 URL)

javascript - 当javascript进入无限循环和递归调用时如何调试javascript?

javascript - 使用 Service Worker 缓存/优化字体

javascript - 检测 JavaScript

javascript - 如何设置机器人事件

在我看来,每条记录的 JavaScript

javascript - 仅在 MVC 中使用 div 在布局和表格中进行渲染,无需表格标签