1

I have a function that is triggered using .onload. I'd like return a value:

newImg.onload = function() {
    var height = newImg.height;
    var width = newImg.width;
    if(height > width){
        console.log(false);
        return false;
    } else {
        console.log(true);
        return true;
    }
 }
 newImg.src = imgSrc; // this must be done AFTER setting onload

Normaly I'd do something like

var foo = function(){...

but this doesn't work in this case. What should I do instead?

4

2 回答 2

4

Asynchronous calls can not return values. You would need to use a callback like you would do in an Ajax request.

function loadImg (imgSrc, callback) {
    var newImg = new Image();
    newImg.onload = function() {
        var height = newImg.height;
        var width = newImg.width;
        if(height > width){
            console.log(false)
            if(callback) callback(false);
        } else {
            console.log(true)
            if(callback) callback(true);
        }
     };
     newImg.onerror = function () {
         if(callback) callback('error');
     };
     newImg.src = imgSrc;

}

loadImg("foo.gif", function(status) { console.log("Do Next Step"); })
于 2013-05-16T12:21:47.183 回答
0

You have two options;

  1. Set the value to another variable.

    var foo;
    
    newImg.onload = function () {
        foo = true;
    };
    
    // Sometime later read `foo`.
    

    ... albeit this is prone to disaster, as you can't guarantee when the variable will be set, as the image will take some amount of time to load.

  2. A better option would be to call another function, pass the value you want to pass, and handle it accordingly then.

    newImg.onload = function () {
        foo(true);
    };
    
    function foo(result) {
        // do something with result
    }
    
于 2013-05-16T12:21:15.923 回答