return value calculated from javascript FileReader onload event [duplicate]

倾然丶 夕夏残阳落幕 提交于 2020-07-18 11:50:33

问题


I have this function:

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

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.


回答1:


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


来源:https://stackoverflow.com/questions/29845232/return-value-calculated-from-javascript-filereader-onload-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!