首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >回调中的Break for循环

回调中的Break for循环
EN

Stack Overflow用户
提问于 2018-03-23 10:25:10
回答 4查看 244关注 0票数 2

我只是在学习javascript中的回调,我想要一些关于以下代码的帮助:

(请阅读整篇文章:我意识到没有设置exists )。

代码语言:javascript
复制
       window.addEventListener('load', function(){

    for (let count = 1; count <= 10; count++) {
        var toTest = "pic" + count + "a.jpg";
        var exists;
       imageExists(toTest, function(response){ if(response == true){ console.log("true" + count); exists = true;  } else { console.log("false" + count );  exists = false;}});
       console.log(exists);

       if(!exists){break;}

    }
    });

function imageExists(image_url, callback){
    console.log("processing: " + image_url);
    var http = new XMLHttpRequest();

        http.open('HEAD', image_url, true);
        http.send();
        http.onload = function() {
            console.log(http.status);
            if (http.status != 404)  {
                console.log(image_url + " exists (in imageExists)");
                callback(true);
            } else {
                console.error(image_url + "does not exist (in imageExists)");
                callback(false);
            }
        }

    }

当然,这不起作用,因为它在回调之前检查exists变量。我试着用break替换exists = false;,但这是非法的。

有什么解决方案可以在不完全更改代码的情况下将回调从函数中提取出来?

控制台日志为:

代码语言:javascript
复制
processing: pic1a.jpg
app.js:14 undefined
app.js:56 200
app.js:58 pic1a.jpg exists (in imageExists)
app.js:13 true1
EN

Stack Overflow用户

发布于 2018-03-23 10:47:41

您正在混合同步/异步代码。您将希望使用递归执行循环逻辑。例如:

代码语言:javascript
复制
function imageExists(a,b){
    if(a>b){
        //found all images, we're done
        return;
    }else{
        var image_url = "pic"+a+"a.jpg";
        console.log("processing: " + image_url);
        var http = new XMLHttpRequest();
        http.open('HEAD', image_url, true);
        http.send();
        http.onload = function() {
            console.log(http.status);
            if (http.status != 404)  {
                console.log(image_url + " exists (in imageExists)");
                //image exists, let's check the next one...
                imageExists(a+1,b)
            } else {
                console.error(image_url + "does not exist (in imageExists)");
                //couldn't find image, stopping early (break)
                return;
            }
        }
    }
}

要检查图像1-10的存在,只需调用imageExists(1,10)

票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49441442

复制
相关文章

相似问题

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