Hi, I'm very new to JS and I've been stumped on this problem for more than a day now.
I am trying to automatically extract all valid image src paths from a folder called "planets" in this case and return them as an array
I have a path structure like:
index/planets/png/1.png
index/planets/gif/1.gif
index/planets/gif/2.gif```
etc.
at first I tried not using async tasks
and building my code off of
function isimgpathvalid(path) {
const img = new Image();
img.src = path;
try {
return img.complete && img.naturalHeight !== 0;
} catch (e) {
return false;
}
}
but ran into lots of issues with it returning undefined at some point and breaking everything
so I'm attempting to do this with async promises and the following:
async function folder2src(folder) {
try{
const imgformatfolders = ["png", "gif", "jpg"];
let srcpile = [];
for (let imgformat of imgformatfolders) {
let imgc = 1;
let shouldcontinue = true;
let check = folder + "\" + imgformat + "\" + imgc + "." + imgformat;
while (shouldcontinue) {
try {
await checkimgpromise(check);
console.log("good");
srcpile.push(check);
} catch (error) {
console.log("bad", error);
shouldcontinue = false;
break;
}
imgc++;
check = folder + "\" + imgformat + "\" + imgc + "." + imgformat;
}
}
return srcpile;
}
catch (error){return ["planet"];}
}
function checkimgpromise(src) {
return new Promise(function(resolve, reject) {
var img = new Image();
img.onload = function() {
resolve(src);
};
img.onerror = function() {
reject("Invalid image path: " + src);
};
img.src = src;
});
}
and it's a huuuuuuuuge headache
my browser console throws errors when the next file path does not lead to a valid image, like "planets\png\3.png" and all the code breaks, how do I avoid this? : (