I have struggled for quite a few hours now on the following Problem: I receive an image via input field and need to validate if the ratio is between 1.90 and 1.92. What I need to do is create a Reader, create an Image, get width and height from the loaded image and return true/false.
Now, as mentioned, the file needs loading time and I therefore need some way to process it async. Sadly, I am a total beginner with Promises / Asyncs and need therefore some major help...
The following part is simply the start of my function chain - I check if an image has been uploaded ( radio button is checked .
...
if (document.editWeb.radio_share[1].checked || document.editWeb.radio_share[2].checked) {
let promise = processFile();
promise.then(function(data){
if (!data){return false;}
});
}
...
My processFile Function. To my understading this returns a promise, which is why I try to get the promise in the upper code snipped and return a false for the 'data' that I am getting.
async function processFile(){
try {
let contentBuffer = await getReader();
return new Promise((resolve, reject) => {
let img = new Image;
img.onload = () => {
let ratio = img.width / img.height;
if (ratio > 1.92 ||ratio < 1.90 ){
resolve(false);
}else {
resolve(true);
}
};
console.log(contentBuffer);
})
} catch(err) {
console.log(err);
}
}
The function that lets me get a reader.
function getReader() {
let x = document.getElementById("share_file").files[0];
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => {
resolve(reader.result);
};
reader.onerror = reject;
reader.readAsDataURL(x);
})
As a follow Up: All of this is called in
<input id="saveAndStay" type="submit" name="buttonSaveAndStay" onclick="return checkRequirements(lang , data")>
after which we had
function checkRequirements(lang , data) {
...
if (document.editWeb.radio_share[1].checked === true || document.editWeb.radio_share[2].checked) {
let promise = processFile();
promise.then(function(data){
if (!data){return false;}
});
}
}
}
Important to note is, that if data returns false - checkRequirements should also return false in order to stop sending the request to the server and instead alert the user with a "this image has a wrong ratio".
I hope this clears things up.