Rich Bradshaw
Rich Bradshaw

Reputation: 72975

How to return from an async function

My code looks like this:

myObject.myMethod('imageCheck', function () {
    var image = new Image();
    image.onerror = function() {
        return false;

    };  
    image.onload = function() {
        return true;
    };
    image.src = 'http://www.example.com/image.jpg';         
});

But, it doesn't work, assumedly because my returns only return from the anonymous function, not from the one called imageCheck. How can I rewrite this so that the whole function is returned as true or false?

Upvotes: 3

Views: 3674

Answers (1)

Naftali
Naftali

Reputation: 146300

you have to use callbacks, for example:

myObject.myMethod('imageCheck', function () {
    var image = new Image();
    image.onerror = function() {
        returnCallback(false);

    };  
    image.onload = function() {
        returnCallback(true);
    };
    image.src = 'http://www.example.com/image.jpg';         
});

function returnCallback(bool){
    //do something with bool
}

Upvotes: 6

Related Questions