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
}
Sign up to request clarification or add additional context in comments.

6 Comments

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.
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?
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!
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
@RichBradshaw it would be awesome if you shared the different approach
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.