Javascript 从回调中中断循环
我正在学习javascript中的回调,希望获得以下代码方面的帮助: (请阅读整篇文章:我意识到Javascript 从回调中中断循环,javascript,Javascript,我正在学习javascript中的回调,希望获得以下代码方面的帮助: (请阅读整篇文章:我意识到存在未设置) 一个足够简单的解决方案是将侦听器转换为异步函数,将imageExists转换为Promise,然后等待它: window.addEventListener('load',异步函数(){ 对于(让count=1;count这是一种非常常见的情况,我们应该使用promise和async/waitfor。这种方法也是重构现有代码时花费最小努力的方法。您可以使用imageExists()转换为
存在
未设置)
一个足够简单的解决方案是将侦听器转换为异步函数,将
imageExists
转换为Promise
,然后等待它:
window.addEventListener('load',异步函数(){
对于(让count=1;count这是一种非常常见的情况,我们应该使用promise
和async
/wait
for。这种方法也是重构现有代码时花费最小努力的方法。您可以使用imageExists()
转换为返回promise
对象的函数,然后它将能够用作:
result = await imageExists(imgUrl);
而不是:
imageExists(imgUrl, callback(result) => {...});
想学习更高级的技能,请去图书馆看看。所以,我认为:
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;
}
您正在混合同步/异步代码。您需要使用递归执行循环逻辑。例如:
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)
我的建议的可能重复之处在于学习如何在一个纯粹的功能性世界中表达自己,而不是你似乎被困在这个准功能性、准程序性的世界中。将功能性代码转换为程序性代码比将程序性代码转换为功能性代码更容易(基本上就是你将要做的)…以函数形式进行重构更容易。重申:你可能不应该使用break
,因为break
是一个过程性的习惯用法,它不能优雅地将其效果扩展到你在这里使用的函数性习惯用法之外。谢谢。我看到了“wait”和“promise”在我的教程中有几个主题。我想我是在不知道的情况下尝试这么做的。
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;
}
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;
}
}
}
}