javascriptdom-eventsonloadonerror

Passing value from image.onload to the surrounding function


I want to know if an image path exists, so I load the image with Javascript using onload and onerror:

Handlebars.registerHelper('image', function(submission_id, point_id) {
    var picture = new Image();

    picture.onload = function() {
        alert('test');
        result = '<img src="' + picture.src + '" />';
    };
    picture.onerror = function() {
        result = '0';
    };
    picture.src = 'static/uploads/submissions/' + submission_id + '/' + point_id + '.png';
    return result;
});

Onload and onerror is working because if the path is correct, I get the alert "test". But the problem is, returning of result doesn't work. I know, it doesn't work because onload is called asynchronously and fired after the returning of result. But how can I solve this?


Solution

  • Because the code is asynchronous, the return statement wont work. Instead what you need to do is define a function, (known as a callback) which is called when the image is loaded. Then your code would look something like this.

    var picture = new Image();
    picture.src = "something";
    picture.onload = function() {
        callback(picture);
    } 
    

    And then the callback would look like this.

    var callback = function(picture) {
        doSomething(picture);
    }
    

    You can read more about callbacks here.