首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >未捕获SyntaxError:非法的break语句

未捕获SyntaxError:非法的break语句
EN

Stack Overflow用户
提问于 2017-12-26 17:23:48
回答 1查看 4K关注 0票数 -1

我收到错误消息

未捕获SyntaxError:非法的break语句

break;上,如果服务器返回5,我想停止for循环。我使用以下代码:

代码语言:javascript
复制
<script type="text/javascript">
    function getrblstatus(rbl, hash) {
        var rblhosts = [<?php echo $rblhosts ?>];
        var ActiveRbls = rblhosts.length;
        var progress = '1';
        for (i = 0; i < ActiveRbls; i++) {
            ///// Post data to server /////
            $.ajax({
                url: '<?php echo $site_url?>/includes/lib/ajax.php',
                data: {
                    action: 'getrblstatus',
                    for: rbl,
                    hash: hash,
                    rbl_host: rblhosts[i]
                },
                type: 'post',
                success: function (data) {
                    var percent = (progress/ActiveRbls)*100;
                    percent = percent.toFixed(2);
                    if(data == 5) {
                        console.log('Hash not correct');
                        break;
                    }
                    else{
                        $('#rbl_table > tbody').append(data);
                        $('#progressbar').width(percent+'%');
                        $("#progressbar").html(percent+"% Completed");
                        progress ++;
                        continue;
                    }
                }
            });
        }
    }
</script>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-26 18:00:33

不能将异步代码( AJAX调用)与同步代码(for/break/continue)混合使用。因此,您可以对AJAX请求执行await

代码语言:javascript
复制
async function getrblstatus(rbl, hash) {
    var hosts = [<?php echo $rblhosts ?>], progress = 1;
    for (const rbl_host of hosts) {
        const data = await new Promise((success, error) => $.ajax({
            url: '<?php echo $site_url?>/includes/lib/ajax.php',
            data: {
                action: 'getrblstatus',
                for: rbl,
                hash: hash,
                rbl_host
            },
            type: 'post', success

        }));
        var percent = (progress++ / hosts.length) * 100;

        if(data == 5) {
            console.log('Hash not correct');
            break;
        }
        else {
            $('#rbl_table > tbody').append(data);
            $('#progressbar').width(percent+'%');
            $("#progressbar").html(percent+"% Completed");
        }
    }
}

由于awaitbreak;处于for循环级别。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47976384

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档