mkw*_*wng 14 javascript csv d3.js
我正在使用D3 将其他 CSV文件列表的CSV 加载到javascript中.
当我运行以下代码时,employees数组在代码中到达它时仍然是空的.有没有一种正确的方法来确保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 "[]"
Run Code Online (Sandbox Code Playgroud)
如果我在Chrome中加载页面,当我进入控制台并记录员工时,肯定会返回充满名称的数组.当我在最后一行运行console.log(employees)时,我该怎么做?
enj*_*lot 20
您可以使用queue.js从所有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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6538 次 |
| 最近记录: |