如何从异步函数返回 [英] How to return from an async function
本文介绍了如何从异步函数返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码如下:
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';
});
但是,它不起作用,可能是因为我的返回仅从匿名函数返回,而不是从名为imageCheck的函数返回.我该如何重写它,以使整个函数返回为true或false?
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?
推荐答案
您必须使用回调,例如:
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
}
这篇关于如何从异步函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文