如何确保D3完成加载几个CSV之前javascript运行? [英] How do I ensure D3 finishes loading several CSVs before javascript runs?

查看:289
本文介绍了如何确保D3完成加载几个CSV之前javascript运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用D3将其他 CSV文件列表的CSV加载到javascript中。

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

当我运行以下代码时, employees数组在代码中的时候仍然为空。是否有正确的方法来确保D3在javascript继续之前完成加载数据?

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

如果我在Chrome中加载页面,当我进入控制台和日志员工,确定足够返回填充名称的数组。

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?

推荐答案

你可以在最后一行运行console.log可以使用 queue.js 收集所有d3.csv通话的结果:

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

这篇关于如何确保D3完成加载几个CSV之前javascript运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆