简体   繁体   中英

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?

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)
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM