I've seen multiple questions like this here but all of them just use alert
or console.log
as the result and I have a different problem.
I'm trying to verify if an image url is valid using async/await
and axios
.
async function checkImageUrl(imageUrl) {
let result = false;
const promise = await axios.get(imageUrl);
promise.then(() => {
console.log('result TRUE');
result = true;
}).catch(() => {
console.log('result false');
result = false;
});
console.log(result);
return result;
}
the image urls are in a json array. I use this in another function like this:
let imageValid = false;
someJson.some((obj) => {
if (obj?.image != null) {
imageValid = checkImageUrl(obj.image);
console.log(imageValid);
if (!imageValid) return true;
}
return false;
});
if (!imageValid) {
return;
}
I've used some console.log
s to check the results. The problem is I never see those logs in async function and console.log(imageValid)
always prints a Promise
object in console. Is can't figure out how to implement this the right way.
You cant use async-await
in some function. You can use tradition for-loop. Same time you can clean up the checkImageUrl
function
function checkImageUrl(imageUrl) {
return axios
.get(imageUrl)
.then((x) => true)
.catch((x) => false);
}
async function main() {
let imageValid = false;
for (let index = 0; index < someJson.length; index++) {
const obj = someJson[index];
if (obj?.image != null) {
imageValid = await checkImageUrl(obj.image);
if (imageValid) {
break;
}
}
}
if (!imageValid) {
return;
}
}
main();