I am just learning about callbacks in javascript and wanted some help with the following code:
(please read entire post: I realise that exists
is not set).
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);
}
}
}
Of course this doesn't work because it is checking exists
variable before the callback. I tried replacing exists = false;
with break
but this this was illegal.
Any solutions to get the callback out of the function without completely changing the code?
Console log is:
processing: pic1a.jpg
app.js:14 undefined
app.js:56 200
app.js:58 pic1a.jpg exists (in imageExists)
app.js:13 true1