我只是在学习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变量。我试着用break替换exists = false;,但这是非法的。
有什么解决方案可以在不完全更改代码的情况下将回调从函数中提取出来?
控制台日志为:
processing: pic1a.jpg
app.js:14 undefined
app.js:56 200
app.js:58 pic1a.jpg exists (in imageExists)
app.js:13 true1发布于 2018-03-23 10:47:41
您正在混合同步/异步代码。您将希望使用递归执行循环逻辑。例如:
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)
https://stackoverflow.com/questions/49441442
复制相似问题