从回调中断开循环

时间:2018-03-23 02:25:10

标签: javascript

我只是在学习javascript中的回调,并希望获得以下代码的帮助:

(请阅读整篇文章:我发现exists未设置)。

       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变量。我尝试用exists = false;替换break,但这是非法的。

任何解决方案都可以在不完全更改代码的情况下从函数中获取回调?

控制台日志是:

processing: pic1a.jpg
app.js:14 undefined
app.js:56 200
app.js:58 pic1a.jpg exists (in imageExists)
app.js:13 true1

4 个答案:

答案 0 :(得分:1)

这是一个非常常见的情况,我们应该使用promiseasync / await。这种方法也是在重构现有代码方面花费最少的方法。您可以将imageExists()转换为返回promise对象的函数,然后它就可以用作:

result = await imageExists(imgUrl);

而不是:

imageExists(imgUrl, callback(result) => {...});

想要了解更多高级技能,请查看ReactiveX图片。

答案 1 :(得分:0)

一个简单的解决方案是将侦听器转换为异步函数,将imageExists转换为Promise,并将await转换为:

&#13;
&#13;
window.addEventListener('load', async function() {
  for (let count = 1; count <= 10; count++) {
    const toTest = "pic" + count + "a.jpg";
    const response = await imageExists(toTest);
    const exists = response.ok;
    if (!exists) {
      console.log('does not exist');
      break;
    }
  }
}

function imageExists(image_url) {
  console.log("processing: " + image_url);
  return fetch(image_url, { method: 'HEAD' });
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

所以,我想:

function imageExists(image_url, callback) {
    console.log("processing: " + image_url);
    var img = document.createElement("IMG");
    img.load = function() { callback(true); };
    img.error = function() { callback(false); };
    img.src = image_url;
    }

答案 3 :(得分:0)

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

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)

即可