如何从异步函数返回

Ric*_*haw 3 javascript asynchronous

我的代码看起来像这样:

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';         
});
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用,假设因为我的返回仅从匿名函数返回,而不是从名为imageCheck的函数返回.我怎样才能重写这个,以便整个函数返回true或false?

Nea*_*eal 6

你必须使用回调,例如:

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
}
Run Code Online (Sandbox Code Playgroud)

  • @RichBradshaw如果你分享不同的方法会很棒 (2认同)