3

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?

1
  • What is myMethod and what is imageCheck? Why are you returning something in a handler function for an async call? That return data does not do anything. You have to use the "continuation" style of programming for async. Commented Apr 28, 2011 at 9:53

1 Answer 1

6

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
}
6
  • Yup. That's definitely the way to go. In case you wanted to be pedantic you could apply true/false partially to returnCallback and avoid extra function definitions. This is more "functional" way to do the same thing. Either way works. Commented Apr 27, 2011 at 19:22
  • In this case, the myObject.myMethod is actually from a 3rd party library, so I have to ensure that that function returns true or false. How do I use this technique to do that? Commented Apr 27, 2011 at 19:27
  • Basically the myObject.myMethod('imagecheck',function () {} ); needs to return either true or false. If it wasn't an async check, I'd just finish with return bool;, but I can't work out how to wait until onerror or onload has fired, then return with the boolean. I might not understand this topic enough, so if that doesn't make sense, then I need to read up more on async stuff! Commented Apr 27, 2011 at 20:52
  • async cannot do a return. this is bc the js runs through the whole script even if it is not done yet, so when the async is done and it needs to do something, so the only way to simulate a return is by making a callback fn
    – Naftali
    Commented Apr 27, 2011 at 20:54
  • 2
    @RichBradshaw it would be awesome if you shared the different approach
    – Damon
    Commented Feb 21, 2013 at 16:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.