2

I am using this lib to resize and compress images before upload

I resize my images like this:

var imgOne = $('#u-fileUpload-1')[0].files[0];
var imgTwo = $('#u-fileUpload-2')[0].files[0];

      if (imgOne !== undefined) {
        ImageResizer.resizeImage(imgOne, resizeOptions, function(result) {
          _this.imgArray.push(result);
        });
      }

      if (imgTwo !== undefined) {
        ImageResizer.resizeImage(imgTwo, resizeOptions, function(result) {
          _this.imgArray.push(result);
        });
      }

I resize my images and store them in a array called imgArray The only problem is that these functions are asynchronous. So my code ends up posting/uploading the form with imgArray being empty since the resize functions has not finished.

So is there any way to chain these functions or check when they both is done?

Thanks

Community
  • 1
  • 1
Kiow
  • 870
  • 4
  • 18
  • 32
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Jun 21 '17 at 14:58
  • You know what asynchronous is, you know the functions are async.. yet you didn't post the code that uses this array that you're populating. So the question is - why? Why was that code left out and why would you try to mix sync/async together? – Mjh Jun 21 '17 at 14:58
  • Implement it with Promises And use Promise.all success callback to post the form. – Hoyen Jun 21 '17 at 15:03

2 Answers2

0

You can make a function that just takes an array of images to resize and a callback:

function resizeImages(imgs, callback) {
    var resizedImages = [];
    for (var i = 0; i < imgs.length; i++) {
        ImageResizer.resizeImage(imgs[i], resizeOptions, function(result) {
            resizedImages.push(result);
            if (resizedImages.length === imgs.length) {
                callback(resizedImages);
            }
        });
    }
}

And use it:

var imgOne = $('#u-fileUpload-1')[0].files[0];
var imgTwo = $('#u-fileUpload-2')[0].files[0];

resizeImages([imgOne, imgTwo], function(resizedImages) {
    //do work with resizedImages
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

Handle it as an array of async functions (promises) DOC

let imgArr = [img1,img2, ..... ];

var resizeArr = [];
imgArr.forEach(img => {
    let p = new Promise((resolve, reject) => {
      (function(cImg){
         ImageResizer.resizeImage(cImg, resizeOptions, function(result) {
            resolve(result);
         });
      })(img);
    });
    resizeArr.push(p);
})

Promise.all(resizeArr).then(resizedImgs => {
   //process new images
})

FIDDLE

Vanojx1
  • 5,574
  • 2
  • 23
  • 37