I have that problem almost a week. I read a lot articles about Promise and how to return value, I even ask from the ChatGPT. But all solutions doesn't work.
Look example: I have condition with 4 functions. Every function execute an one check: (
- One check quantity of files,
- Second summary size of files,
- Third Type of file and
- Fourth - dimension on side Image
) it look like that:
if(
this.checkQuantityFiles(filesArr)&&
this.checkTotalFilesSize(filesArr)&&
this.checkType(filesArr)&&
this.checkImageDimension(filesArr)
)
I did all functions beside checkImageDimension, cause that function consist a load image for which need a Promise.
checkImageDimension(files:File[]):boolean{
function isValidImage(image: HTMLImageElement): boolean {
return image.width < MAXLIMITWIDTH && image.height < MAXLIMITHEIGH;
}
function loadImage(file: File): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = reject;
image.src = URL.createObjectURL(file);
});
}
async function checkArray(){
const imagePromises = files.map(loadImage);
const images = await Promise.all(imagePromises);
const every:Promise<boolean>=new Promise((resolve)=>{
resolve( images.every(isValidImage))
})
const result=await every.then((res)=>{
return res
})
console.log(result);
return result
}
const result= checkArray().then((result)=>{return result},()=>{
throw Error("Check array function invalid")
})
return result//// I should return boolean here but i can't make boolean from Promise<boolean>
}
I tried set "await", use "then". But compiler don't give me return boolean if I have async function and remove async function - i can't set await and unwrap Promise. If i make an const and link her with async func as at the end my code I also to get Promise. Why?? I should to get value. Promise is finish.