如何立即更新从异步FileReader函数初始化的变量?

时间:2015-10-19 11:55:15

标签: javascript jquery asynchronous filereader

我正在尝试使用FileReader将csv文件的内容保存到变量中。我设法获取内容并将其保存到变量csvAreas中,但不会立即更新。我尝试过回调方法 jquery $ .when()。然后(),但它仍无效。

test.csv:

c1,23.44308893,53.06396484
c2,23.73506919,54.0637207
c3,23.01907619,53.12988281

main.js:

var csvAreas = [];

// other stuff..

function csvImport(){
    $.when(csvLoad()).then(drawCSVCoverage());
}

function csvLoad(){
    var file = document.getElementById("csv-file-upload").files[0];

    readFile(file, function(e) {
        var lines = this.result.split('\n');
        for(var line = 0; line < lines.length; line++){
            var cols = lines[line].split(',');
            csvAreas.push([]);
            csvAreas[line].push(cols[1]);
            csvAreas[line].push(cols[2]);
        }
    });
}

function readFile(file, onLoadCallback){
    var reader = new FileReader();
    reader.onload = onLoadCallback;
    reader.readAsText(file);
}

function drawCSVCoverage(){
    alert("Length: " + csvAreas.length) //Length: 0
}

但是,如果我第二次发出警报,alert(csvAreas.length)将产生实际价值。

function drawCSVCoverage(){
    alert("Length: " + csvAreas.length) //Length: 0
    alert("Length: " + csvAreas.length) //Length: 3
}

警报会导致浏览器更新变量吗?有没有正确的方法来更新变量?

0 个答案:

没有答案