从javascript FileReader onload事件计算得出的返回值 [英] return value calculated from javascript FileReader onload event

查看:906
本文介绍了从javascript FileReader onload事件计算得出的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能:

function doStuff(range, file) {
    var fr = new FileReader();
    var hash = '';
    fr.onload = function (e) {
        var out = "stuff happens here";
        hash = asmCrypto.SHA256.hex(out);
        return hash;
    };
    fr.readAsArrayBuffer(file);
    return hash;
}

现在,该函数在onload事件完成之前完成,所以doStuff总是返回。我认为回调是我所需要的,但是我是javascript的新手,在这种情况下我无法全神贯注于如何实现它。

Right now, the function completes before the onload event is finished, so doStuff always returns "". I think a callback is what I need, but I'm new to javascript, and I can't wrap my mind around how to implement it in this case.

推荐答案

使用文件读取器读取文件是异步操作。将逻辑放入文件读取器的 onload 函数中。

File reading using File Reader is asynchronous operation. Place your logic inside the onload function of file reader.

function doStuff(range, file) {
    var fr = new FileReader();
    fr.onload = function (e) {
        var out = "stuff happens here";
        hash = asmCrypto.SHA256.hex(out);
        /* Place your logic here */
    };
    fr.readAsArrayBuffer(file);
}

您甚至可以传递将在读取文件后执行的回调函数

You can even pass a callback function that will be executed once the file is read.

function doStuff(range, file, callback) {
    var fr = new FileReader();
    fr.onload = function (e) {
        var out = "stuff happens here";
        hash = asmCrypto.SHA256.hex(out);
        /* Assuming callback is function */
        callback(hash);
    };
    fr.readAsArrayBuffer(file);
}

这篇关于从javascript FileReader onload事件计算得出的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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