15

我正在使用 D3 将其他CSV 文件列表的 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) 时,我怎样才能做到这一点?

4

2 回答 2

21

您可以使用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)
}
于 2012-11-20T18:17:07.367 回答
0

Your code seems fine. It's just that you're logging employees before the data is ready. But if you console.log it on the last line of parseList you should have it.

于 2012-11-17T04:16:50.860 回答