最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to return from an async function - Stack Overflow

matteradmin5PV0评论

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 = '.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?

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./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?

Share Improve this question asked Apr 27, 2011 at 19:13 Rich BradshawRich Bradshaw 73.1k46 gold badges188 silver badges241 bronze badges 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. – Stephen Chung Commented Apr 28, 2011 at 9:53
Add a ment  | 

1 Answer 1

Reset to default 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./image.jpg';         
});

function returnCallback(bool){
    //do something with bool
}
Post a comment

comment list (0)

  1. No comments so far