0

I'm currently fixing an existing code to check image minimum dimensions before upload. I'm now getting the proper size of image thanks to new Image() but I can't return the result! Here's the code :

_hasError: function (file) {
       if (file.error) {
            return file.error;
        }

        if (this.options.minWidth > 0 && this.options.minHeight > 0) {
            var checkSizeUpload = function(minWidth, minHeight) {
                if (this.width < minWidth || this.height < minHeight) {
                    return "Image too small";
                }
            };

            var tmpImg = new Image();
            tmpImg.src = URL.createObjectURL(file);
            tmpImg.onload = checkSizeUpload.bind(tmpImg, this.options.minWidth, this.options.minHeight);
        }

        ...

     return null;
}

As you can see, the method is designed to return null or error message. The trouble is, as the onload callback is asynchronous, I can't find a way to return the error message once I know the actual size of the image.

From what I saw, I might have to add another callback but I can't see how this would help since if I return from it, it won't return in the needed scope.

How can I fix this ? Thanks for your help!

Bambi
  • 1
  • 2
  • If you're depending on an asynchronous call inside your function then by necessity your function becomes asynchronous and you must use asynchronous idioms to call it and process the result. See the duplicate. – deceze May 20 '15 at 10:13
  • @deceze Thanks for the detailed link but I really would have love to have an actual example in my specific case, even in pseudo-code, on how on far I need to change the structure since it belongs to a much large library, and I'm not using ajax. – Bambi May 20 '15 at 10:30
  • @deceze could you let me get some help before marking it as duplicate please? – Bambi May 20 '15 at 10:39
  • Essentially you just need to accept a callback function: `_hasError: function (file, callback)`, and instead of `return ..` you do `callback(..)`. Does that help? Have you tried something like that? – deceze May 20 '15 at 11:37
  • @deceze it was a good start yes! thanks! – Bambi May 20 '15 at 17:00

0 Answers0