0

I have a function that works in the console when i step through it but doesn't work on the device when i run it normally.

I think the problem is the callback(t) runs before the result of the render function has finished.

var MAX_HEIGHT = 740;
    function render(src) {
        var image = new Image();
        image.src = src;
        var out = '';
        image.onload = function () {
            var canvas = document.createElement("canvas");
            if (image.height > MAX_HEIGHT) {
                image.width *= MAX_HEIGHT / image.height;
                image.height = MAX_HEIGHT;
            }
            var ctx = canvas.getContext("2d");
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            canvas.width = image.width;
            canvas.height = image.height;
            ctx.drawImage(image, 0, 0, image.width, image.height);
            console.log('resized: ', canvas.toDataURL("image/jpeg", 1.0));
            out = canvas.toDataURL("image/jpeg", 1.0);
        };
        return out;
    }


function toDataUrl(url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = function () {
            var reader = new FileReader();
            reader.onloadend = function () {
                var t = render(reader.result);
                callback(t);
                console.log(t);
            };
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.send();
    }

How can I make it so the callback() only runs once the render() has finished

StudentRik
  • 1,049
  • 2
  • 20
  • 37
  • Use a [Promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) instead. – str Nov 23 '16 at 12:52
  • Thanks I will have a look at that. – StudentRik Nov 23 '16 at 12:54
  • Instead of waiting for the filereader you could use `URL.createObjectURL(file)` which is synchronous - then you don't have to wait for something and it's faster too – Endless Nov 23 '16 at 17:59

0 Answers0