如何使用javascript同步读取csv文件并从中返回值

时间:2019-04-13 18:32:27

标签: javascript filereader synchronous

我正在通过一个名为findAbbreviation(fullName)的函数传递全名 我使用的是全名,缩写对的csv文件,以返回与全名匹配的缩写的值。 考虑到我要同步读取csv,最好的方法是什么?

d3.csv(“ candy.csv”,function(csv){

//reformat the locations to have a consistent format
//every entry in q5 is changed to an abbreviation of 2 letters
//the abbreviation lists are in the folder named such
var updatedAbbr = csv.map(function(d) {

    //check to see the entry has a value
    if (d.Q5_STATE != null) {

        //the country is the united States
        if (d.Q4_COUNTRY == "United States") {

            //if the state value is longer than two characters, set it to UU
            if (d.Q5_STATE.length > 2) {
                d.Q5_STATE = findAbbreviation(d.Q5_STATE);  
            }

            //pass through and check that the new value is not null
            if (d.Q5_STATE != null) {
                console.log(d.Q5_STATE);    
            }


        }
    }
});

});

function findAbbreviation(fullName){

}

我想传递值Alabama并获得AL。或加利福尼亚-> CA。

1 个答案:

答案 0 :(得分:0)

d3.csv是异步的,您对此无能为力。

您可以使用XMLHttpRequest发出同步请求(危险:不推荐使用此功能),然后通过d3.csv.parse传递结果。

我建议改用异步编程。