从异步 JavaScript 方法返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6211023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:52:25  来源:igfitidea点击:

Returning value from asynchronous JavaScript method?

javascriptasynchronousmethodsreturn

提问by Kevin

I have run into a problem where I can't seem to get a value from an asynchronous JavaScript method I am running in Jquery. My Jquery looks like this:

我遇到了一个问题,我似乎无法从我在 Jquery 中运行的异步 JavaScript 方法中获取值。我的 Jquery 看起来像这样:

$(document).ready( function() {
$('#splash_image_upload').change( function() {
    var file = this.files[0];
    var blob_string = create_blob(file);
    alert(blob_string);
 });

I am able to access the value that comes from the 'onload' event but I cannot seem to return the actual value. I have tried this:`

我能够访问来自 'onload' 事件的值,但我似乎无法返回实际值。我试过这个:`

function create_blob(file) {
    var reader = new FileReader();
    reader.onload = (function() { return function(e) { return e.target.result; }; })();
    reader.readAsDataURL(file);
}

Every time I execute this function the value of the 'blob_str' variable is 'undefined' presumably because the assignment is done before the function is finished. I am not really sure how to go about this. Is there a way I can return this value from this function??

每次我执行这个函数时,'blob_str' 变量的值都是 'undefined' 大概是因为赋值是在函数完成之前完成的。我不太确定如何解决这个问题。有没有办法可以从这个函数返回这个值??

回答by mu is too short

Your best bet is to pass a callback to create_bloband let the callback do whatever needs to be done, something like this:

最好的办法是将回调传递给create_blob并让回调做任何需要做的事情,就像这样:

create_blob(file, function(blob_string) { alert(blob_string) });

function create_blob(file, callback) {
    var reader = new FileReader();
    reader.onload = function() { callback(reader.result) };
    reader.readAsDataURL(file);
}

This sort of chicanery is pretty standard with asynchronous calls (AJAX in particular). You could wire up some fragile mess of timers in an attempt for force synchronically but fighting the natural style of an API is a losing battle.

这种诡计对于异步调用(尤其是 AJAX)来说是非常标准的。您可以连接一些脆弱的计时器以尝试同步强制,但与 API 的自然风格作斗争是一场失败的战斗。

回答by ic3

This is the issue with callbacks. The 'answer' is going to happen later in another moment and not during the evaluation of the method. Little use making a return here.

这是回调的问题。“答案”将在稍后的时间发生,而不是在评估方法的过程中。在这里返回几乎没有用。

Your callback needs to handle the return value making the code looks more complicated :

您的回调需要处理返回值,使代码看起来更复杂:

reader.onload = function(e) { 
  // handle here the result
  // do something with e.target.result
};