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

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

问题描述

我遇到了一个问题,我似乎无法得到一个异步JavaScript的方法,我在jQuery的运行值。我的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变量值未定义presumably因为分配完成该功能前完成。我真的不知道如何去这一点。有没有一种方法可以让我从这个函数返回这个值?

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

这有点欺骗的是异步调用pretty标准(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天全站免登陆