just to start off I am pretty new to javascript.
I am using an library to resize images. The problem here is that the function returns the variable imgBlob before the library has finished resizing, which results in imgBlob being "undefined".
I am using below code:
function resizeImage(fileInput) {
var imgBlob;
ImageTools.resize(fileInput.files[0], {
width: 320, // maximum width
height: 240 // maximum height
}, function (blob, didItResize) {
// didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
if (didItResize == true) {
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
imgBlob = reader.result;
}
} else {
// error message ?
}
});
return imgBlob;
}
document.getElementById('verzenden').onclick = function() {
var imgBlobs = [];
var imgHuisnummerField = document.getElementById('imgHuisnummer');
if (imgHuisnummerField.value != "") {
imgBlobs.push(resizeImage(imgHuisnummerField)); //pushes "undefined" to the array.
}
How am I able to wait for the whole resizeImage function to finish before it returns the imgBlob? I have tried using async with await, but that leaves a 'Promise' which doesn't work as expected.
The async attempt:
async function resizeImage(fileInput) {
var imgBlob;
await ImageTools.resize(fileInput.files[0], {
width: 320, // maximum width
height: 240 // maximum height
}, function (blob, didItResize) {
// didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
if (didItResize == true) {
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
imgBlob = reader.result;
}
} else {
// error message ?
}
});
return imgBlob;
}
It returns a promise which doesnt get solved..