我正在加载 CSV 列表other使用 D3 将 CSV 文件转换为 javascript。
当我运行以下代码时,当它在代码中到达员工数组时,它仍然是空的。有没有正确的方法来确保 D3 在 javascript 继续之前完成数据加载?
var employees = [];
//Retrieve the file list of all the csvs in the data directory, then run a callback on them
function retrieveList(url,callback) {
d3.csv(url,function(data) {
callback(data);
})
}
//Parse a file list, and then update the employee array with the data within
function parseList(filenames){
filenames.forEach(function(d) {
d3.csv(d.filename,function(data) {
data.forEach(function(d) employees.push(d.name));
}
}
}
//Run this code
var filenamesUrl = "http://.../filenames.csv"
retrieveList(filenamesUrl, parseList);
console.log(employees); //This logs "[]"
如果我在 Chrome 中加载页面,当我进入控制台并记录员工时,果然它会返回充满姓名的数组。当我在最后一行运行 console.log(employees) 时,如何才能做到这一点?
你可以使用queue.js https://github.com/mbostock/queue收集所有 d3.csv 调用的结果:
function parseList(filenames){
var q = queue();
filenames.forEach(function(d) {
//add your csv call to the queue
q.defer(function(callback) {
d3.csv(d.filename,function(res) { callback(null, res) });
});
});
q.await(restOfCode)
}
function restOfCode(err, results) {
//results is an array of each of your csv results
console.log(results)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)