Suppose, we want to check the width of an image before uploading it. Here is the fiddle. In the end we need to wait for the end of all the asynchronous operations. I tried to use Promises for this purpose. But, unfortunately, good_images are empty inside alert. Seems, that I'm missing something simple.
I tried Promise.all, but it also doesn't work. Fiddle.
$(document).ready(function () {
function check_image_dimensions ($this, image, img_name) {
let min_width = + $this.data('min_width');
if (typeof(min_width) === "number" && image.width < min_width) {
alert(`Error loading photo ${img_name}, image width: ${image.width}px is less then minimal: ${min_width}px.`);
return false;
}
return true;
}
function unknown_error () {
alert('Unknown error while loading image.');
}
$(document).on('change', '.upload_images', function() {
var $this = $(this);
let images = $this.prop('files');
if (typeof(images) === 'undefined' || images.length === 0) {
return false;
}
let good_images = Array();
let promise = Promise.resolve();// <- I tried this, but it is wrong
for (let i = 0; i < images.length; i++) {
let promise = new Promise(function(resolve, reject) {
const reader = new FileReader();
reader.onload = resolve;
reader.readAsDataURL(images[i]);
});
promise.then((event) => {
const img = new Image();
img.onload = () => {
if(check_image_dimensions($this, img, images[i].name) === true) {
good_images.push(i);
}
};
img.onerror = unknown_error;
img.src = event.target.result;
return i;
}).catch(unknown_error);
}
promise.then(() => alert(good_images));
});
});