简体   繁体   中英

Is FileReader take more time to load?

Below is my code

var uploadIDImage = {
    IDPos: {},
    IDNeg: {}
};

var FR = new FileReader();

FR.onload = function(e) {
    console.log("123");
    console.log(e);
    $("#UploadIDPos img").remove();
        $("#UploadIDPos i").hide();
    $('#UploadIDPos').prepend('<img id="IDPosImg" style="width: 140px; height: 80px;"/>');
    var img = document.getElementById('IDPosImg');
  img.src = FR.result;
    uploadIDImage.IDPos.Files = FR.result.split(",")[1];
    console.log("11111");
};

if(e.target.files[0]) {
    FR.readAsDataURL(e.target.files[0]);  
    if(originalIDPosSize === undefined) {
            var size = Math.round(e.target.files[0].size / 1024 / 1024);
            originalIDPosSize = size;
        }
        else {
            totalSize  = totalSize + originalIDPosSize; 
            var size = Math.round(e.target.files[0].size / 1024 / 1024);
        }
        var remainSize = totalSize - size;
        console.log("Remain size : " + remainSize);
        $("#remain-size").text(totalSize - size);
        totalSize = remainSize;
} 

console.log("22222");
console.log(uploadIDImage.IDPos.Files);

What I got from my console.log is first print "22222" and undefined and then "111111".

Why "11111" not print first?

When you do

FR.onload = function(e) {... }

you are setting a callback on the FileReader which is called when the reading operation has successfully completed.

Now you script proceeds and runs console.log("22222");

After a while the callback is invoked and you see the 11111 .

Your section of code FR.onload = function(e) { ... } is just defining a handler for the FR object. The FileReader methods like readAsDataURL() are asynchronous -- your program continues after it executes the FR.readAsDataURL(...) statement.

Then later, when the file reading is done, then the function you specified for FR.onload runs. It is indeterminate whether this happens before or after your console.log("22222"); statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM