简体   繁体   English

如何从异步 function 返回

[英]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.但是,它不起作用,假设是因为我的回报仅来自匿名 function,而不是来自名为 imageCheck 的回报。 How can I rewrite this so that the whole function is returned as true or false?我怎样才能重写这个,以便整个 function 返回为真或假?

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM