Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ensure D3 finishes loading several CSVs before javascript runs?

I'm loading a CSV of a list of other CSV files into javascript using D3.

When I run the following code, the employees array is still empty by the time it gets to it in the code. Is there a correct way to ensure that D3 finishes loading the data before the javascript continues?

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 "[]"

If I load the page in Chrome, when I go into console and log employees, sure enough it returns the array filled with names. How can I make that the case by the time I run console.log(employees) on the last line?

like image 462
mkwng Avatar asked Nov 16 '12 23:11

mkwng


1 Answers

You could use queue.js to collect the results from all the d3.csv calls:

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)
}
like image 96
enjalot Avatar answered Oct 23 '22 16:10

enjalot