从异步 JavaScript 方法返回值? [英] Returning value from asynchronous JavaScript method?

查看:32
本文介绍了从异步 JavaScript 方法返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

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:`

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

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

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

推荐答案

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

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

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);
}

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

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.

这篇关于从异步 JavaScript 方法返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆